Writing to a file

suggest change
with open('myfile.txt', 'w') as f:
    f.write("Line 1")
    f.write("Line 2")
    f.write("Line 3")
    f.write("Line 4")

If you open myfile.txt, you will see that its contents are:

Line 1 Line 2 Line 3 Line 4

Python doesn’t automatically add line breaks, you need to do that manually:

with open('myfile.txt', 'w') as f:
    f.write("Line 1\n")
    f.write("Line 2\n")
    f.write("Line 3\n")
    f.write("Line 4\n")
Line 1 Line 2 Line 3 pyLine 4

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use \n instead.

If you want to specify an encoding, you simply add the encoding parameter to the open function:

with open('my_file.txt', 'w', encoding='utf-8') as f:
    f.write('utf-8 text')

It is also possible to use the print statement to write to a file. The mechanics are different in Python 2 vs Python 3, but the concept is the same in that you can take the output that would have gone to the screen and send it to a file instead.

with open('fred.txt', 'w') as outfile:
    s = "I'm Not Dead Yet!"
    print(s) # writes to stdout
    print(s, file = outfile) # writes to outfile

    #Note: it is possible to specify the file parameter AND write to the screen
    #by making sure file ends up with a None value either directly or via a variable
    myfile = None
    print(s, file = myfile) # writes to stdout
    print(s, file = None)   # writes to stdout

In Python 2 you would have done something like

outfile = open('fred.txt', 'w')
s = "I'm Not Dead Yet!"
print s   # writes to stdout
print >> outfile, s   # writes to outfile

Unlike using the write function, the print function does automatically add line breaks.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Files, Folders, I/O:
* Writing to a file

Table Of Contents
2 Filter
3 List
7 Loops
15 Files, Folders, I/O
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve