Skip to main content

10.5) Writing Files


As with reading files, writing to a file involves three steps: (i) opening the file, (ii) writing content, (iii) closing the file. Here is a simple example: 

fid=open('output.txt','w')    # w creates a new file for writing.
fid.write('some text to go in the file\n') # \n  is the end of line character.
fid.write('some more text\n')
fid.close()

In the first line, the 'w' indicates that we want to write to the file. This will erase 'output.txt' if it already exists. If you wish to append to a file use the letter 'a' instead.
Notice that you have to add a newline character (\n) at the end of the string to indicate a new line.
If you data is organised as a list of strings, you can write them all in one go with writelines command:

fid=open('output.txt','w')
content=['first line\n','second line\n','third line\n']
fid.writelines(content)
fid.close()

As you can see, you have to add a newline character (\n) at the end of each string in the list if you want the strings to be printed on separate lines.