Archive
Posts Tagged ‘write’
Reading and writing a file
December 17, 2010
Leave a comment
Here is a mini cheat sheet for reading and writing a text file.
Read a text file line by line and write each line to another file (copy):
f1 = open('./in.txt', 'r')
to = open('./out.txt', 'w')
for line in f1:
to.write(line)
f1.close()
to.close()
Variations:
text = f.read() # read the entire file line = f.readline() # read one line at a time lineList = f.readlines() # read the entire file as a list of lines
