Python file read write examples

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
Env: Python 2.7.6

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
Env: Python 2.7.6

Read whole file

with open("out.txt", "r") as f:
  content = f.read()
  print content
  print f
print f
Env: Python 2.7.6

iterate over lines from file

with open("out.txt", "r") as f:
  for line in f :
    print "=line="
    print line
Env: Python 2.7.6
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments