If you are interested in writing text to a file in Python, there is probably many ways to do it. Here is three ways to write text to a output file in Python. The first step in writing to a file is create the file object by using the built-in Python command “open”. To create and write to a new file, use open with “w” option. The “w” option will delete any previous existing file and create a new file to write. (If you are interested in reading from a text file, check Three ways to read a text file line by line in python.)
# open a (new) file to write >>>outF = open("myOutFile.txt", "w")
If you want to append to an existing file, then use open statement with “a” option. In append mode, Python will create the file if it does not exist.
# open a file to append >>>outF = open("myOutFile.txt", "a")
Once you have created the file object in write/append mode, you can write text in multiple ways. Let us say we have the text that we want to write is in a list “textList”.
>>>textList = ["One", "Two", "Three", "Four", "Five"]
We can write this list to a file either line by line or write all lines at once.
Writing One Line at a Time to a File in Python Using write()
Let us create new file by creating the file object “outF” using “w” option as before. To write line by line, we loop through the textList and get each element and write it to the file.
>>>outF = open("myOutFile.txt", "w") >>>for line in textList: ... outF.write(line) ... outF.write("\n") >>>outF.close()
Note that the elements in the “textList” does not have a new line character “\n”. Therefore, we added that while writing to the file. Otherwise, all five elements will be in a single line in the output file. Also note outF.close() at the end. close() method closes the access to the file. It is a good practice to use the close() method to close a file, once we are done with a file.
Writing One Line at a Time to a File in Python Using “print”
Another way to write one line at a time to a file in Python is to use the print statement. Instead of printing a statement to the scree, we redirect to the output file object.
>>>outF = open("myOutFile.txt", "w") >>>for line in textList: ... print >>outF, line >>>outF.close()
Writing All The Lines at a Time to a File in Python
Python also has a method that can write all lines at the same time to a file. Python’s “writelines()” method takes a list of lines as input and writes to a file object that is open with write/append access. For example to write our “textList”, using “writelines(), we first add the new line to each element. The second statement below (with lambda function) adds the new line to each element.
>>>outF = open("myOutFile.txt", "w") >>>textList = map(lambda x: x+"\n", textList) >>>outF.writelines(textList) >>>outF.close()
You can also make your life simpler using “with” statement in Python to open files. Check out here.