klenwell information services : PythonFileHandling

Python File Handling

return to DevPython

Basics

Read

# file_path assumed valid, 'r' (read) is default mode
f = open(file_path, 'r')
file_lines = f.readlines()
f.close()

print file_path, ':', len(file_lines), 'lines'


Write

# file_lines is a sequence of strings; file_path assumed valid
f = open(file_path, 'w')
for line in file_lines:
	f.write('%s\n' % (line))
f.close()

# verify results
f = open(file_path, 'r')
print '%s:\n\n%s' % (file_path, ''.join(f.readlines()))
f.close()


References

http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files