You can use the following syntax to open a file in Python, do something with it, and then close the file:
file = open('my_data.csv') df = file.read() print(df) file.close()
The problem with this approach is that it’s very easy to forget to close the file.
A better approach is to use with open, which uses the following basic syntax:
with open('my_data.csv') as file: df = file.read() print(df)
Using this approach, the file that you’re working with is automatically closed so that you don’t have to remember to use file.close().
The following examples show how to use with open in different scenarios.
Example 1: Use With Statement to Read File
The following code shows how to use the “with” statement to read a file into Python and print the contents of the file:
with open('my_data.csv') as file: df = file.read() print(df) ,points,assists,rebounds 0,11,5,6 1,17,7,8 2,16,7,8 3,18,9,10 4,22,12,14 5,25,9,12 6,26,9,12 7,24,4,10 8,29,8,11
The contents of the file are printed and the file is automatically closed without us typing file.close().
Example 2: Use With Statement to Write File
The following code shows how to use the “with” statement to write some text out to a file:
with open('data_out.csv', 'w') as file: file.write('Some text to write to CSV file')
Note that the ‘w‘ within the open() statement tells Python to use ‘write’ mode with the file as opposed to read mode.
Example 3: Use With Statement to Read & Write Files
We can also open several files at once within a single “with” statement.
The following code shows how to use the “with” statement to open two files, read the contents of one file, and then write the contents of the first file out to the second file:
with open('my_data.csv', 'r') as infile, open('data_out.csv', 'w') as outfile: for line in infile: outfile.write(line)
If we navigate to the location where we wrote ‘data_out.csv’ then we can view the contents of the file:
Note that we can use the open() function to open as many files as we’d like within a single “with” statement.
The following tutorials explain how to perform other common operations in Python: