We have previously seen how we can read from a file in Python. Similarly writing to a file can also be achieved in Python programming. But, before we start writing to a file, we must ensure that the mode in which the file has been open allows it. Let us take a look using which modes we can actually write to a file.
w– opens the file for writing and creates one file if it doesn’t exist,
w+– opens the file for both writing and reading,
a– opens the file for appending. The data gets appended to the end of the file,
x– creates a new file in writing as well as reading mode,
r+– opens the file for both reading and writing.
So now, let’s see how we can write to a file in Python using different approaches.
1. Python Write File using write() function
write() function, we can actually directly write a string (which is passed as an argument) to a file.
file = open("new_file.txt", "w+") file.write('Using the write() method') file.seek(0) print(file.read())
Using the write() method
2. Using writelines() in Python
writelines() is another pre-defined method in Python which is used to write multiple lines into a specific file, with a list of string elements passed as an argument.
list1=[ ‘ string 1 ‘ ,’ string 2 ‘, …… , ‘ string n ‘]
file_open_object.writelines( list1 )
list1=['Python\n','C\n','C++\n','Java'] file=open("new_file.txt", "w+") file.writelines(list1) file.seek(0) print(file.read())
Python C C++ Java