Python Tutorial Series - Files

In Python, files are opened with the open command. The open command takes two parameters.
The first parameter is the file name. The second parameter is the mode to open the file in:



r - Open the file for reading. An error is thrown if the file does not exist.
a - Open the file for appending to the end of it. The file is created if it doesn't exist.
w - Open the file for writing to it. The file is created if it doesn't exist.
x - Create the file. An error is thrown if the file exists.

t - Open the file as a text file. By default, files are opened in text mode.
b - Open the file as a binary file.


Text Files


Reading



Reading a file using Python is done as follows:



f = open('test.txt', 'r')
f.close()


In the above example, f.close(), will close the file when it's done being read from.
Files may also be opened using a with statement. When using the with statement, f.close() is automatically called:



with open('test.txt', 'r') as file:
    data = file.read()


To read from a file, do the following:



with open('test.txt', 'r') as f:
    data = f.read()


Read a certain number of characters:



with open('test.txt', 'r') as f:
    data = f.read()


Read a single line:



with open('test.txt', 'r') as f:
    data = f.readline()


Read the entire file:



with open('test.txt', 'r') as f:
    for data in f:
        print(data)


Writing





with open('test.txt', 'w') as f:
    f.write('Writing some text content in a file')


Binary Files



Reading





with open('test.txt', 'rb') as f:
    data = f.read()


Writing





with open('test.txt', 'wb') as f:
    f.write("Writing some binary content in a file\n".encode('utf8'))


Go to a position





with open('test.txt', 'rb') as f:
    data = f.seek(10, 20)


More Python





Comments