Python - File Method List


The built-in open function creates a Python file object.

It serves as a link to a file residing on your machine.

After calling open, you can transfer strings of data to and from the associated external file by calling the returned file object's methods.

The following table summarizes common file operations.

output = open(r'C:\test', 'w')
Create output file ( 'w' means write)
input = open('data', 'r')
Create input file ( 'r' means read)
input = open('data')
Same as prior line ( 'r' is the default)
aString =
Read entire file into a single string
aString =
Read up to next N characters (or bytes) into a string
aString = input.readline()
Read next line (including \n newline) into a string
aList = input.readlines()
Read entire file into list of line strings (with \n)
Write a string of characters (or bytes) into file
Write all line strings in a list into file
Manual close (done for you when file is collected)
Flush output buffer to disk without closing
Change file position to offset N for next operation
for line in open('data'): use line
File iterators read line by line
open('f.txt', encoding='latin-1')
Python 3.X Unicode text files (str strings)
open('f.bin', 'rb')
Python 3.X bytes files (bytes strings)'f.txt', encoding='utf8')
Python 2.X Unicode text files (unicode strings)
open('f.bin', 'rb')
Python 2.X bytes files (str strings)

Related Topics