Reading and writing files in python is very common use case. Here are some examples:
Write to file using “with open()”
Here file gets closed automatically outside with block.
with open("out.txt", "w") as f:
f.write("hello world\nhello world2\n")
print f
print f<open file 'out.txt', mode 'w' at 0x7f4a355379c0> <closed file 'out.txt', mode 'w' at 0x7f4a355379c0>
Env: Python 2.7.18
Write to file using “open()”
Here we need to explicitly close the file handle.
f = open("out.txt", "w")
f.write("hello world\nhello world2\n")
print f
f.close()
print f<open file 'out.txt', mode 'w' at 0x7ff4a3c079c0> <closed file 'out.txt', mode 'w' at 0x7ff4a3c079c0>
Env: Python 2.7.18
Read whole file
with open("out.txt", "r") as f:
content = f.read()
print content
print f
print fhello world hello world2 <open file 'out.txt', mode 'r' at 0x7ff34d16c9c0> <closed file 'out.txt', mode 'r' at 0x7ff34d16c9c0>
Env: Python 2.7.18
iterate over lines from file
with open("out.txt", "r") as f:
for line in f :
print "=line="
print line=line= hello world =line= hello world2
Env: Python 2.7.18