To interact with any type of file, we first need to know a bit about some general functions. open(file, mode='r',...)is the first, and is used to open a file. Using the parameter mode, we can here choose how the file is to be opened, as well as what we are able to do with it. The following table is taken from docs.python.org.
Character
Meaning
'r'
open for reading (default)
'w'
open for writing, truncating1 the file first
'x'
open for exclusive creation, failing if the file already exists
'a'
open for writing, appending to the end of the file if it exists
'b'
binary mode
't'
text mode (default)
'+'
open for updating (reading and writing)
1Means removing the file contents without deleting the file.
It is also important to close the file after we are done with it, which we will show in the following examples. If you are unsure why it is important to close the file, please have a look at this post on Stack Overflow discussing the topic.
Closing file - Method 1Expand source
# This is the most intuitive method, as we are explicitly closing the file when we are finished.
# However, if an exception is triggered during the program, the .close-function will not be executed.
# Open the file "input" for reading
fid = open('input.txt', 'r')
# Read the file as wanted...
# Close the file using the .close()-method
fid.close()
# We can verify that the file is closed using the bool .closed
print(fid.closed) # This will print "True"
Closing file - Method 2Expand source
# In this method we take into account that there might be triggered an exception during the program,
# and we make sure to close the file despite this
try: # Try to open the file "input" for reading
fid = open('input.txt', 'r')
# Read the file as wanted...
except: # If an exception is triggered during the try-block
print('Something went wrong when reading to the file')
finally: # Make sure the file is closed independent of an exception or not
fid.close()
# We can verify that the file is closed using the bool .closed
print(fid.closed) # This will print "True"
Closing file - Method 3Expand source
# The third, and by docs.python.org recommended method, is to use the 'with' keyword.
# This makes sure the file is properly closed after the suite finishes,
# but also uses less space than the try-finally blocks.
with open('input.txt', 'r') as fid:
# Read the file as wanted...
# Be aware of this indent!
# The file is automatically and properly closed after the suite finishies
# We can verify that the file is closed using the bool .closed
print(fid.closed) # This will print "True"
Not closing fileExpand source
# Open file for reading
fid = open('input.txt', 'r')
# Read the file as wanted...
# Forgetting to close file
# We can verify that the file is closed using the bool .closed
print(fid.closed) # This will now print "False"
As a final note on how to open files, we will open a file not located in our current directory(this refers to the location of the executed python program/file). To do so, we need to use an absolute path, as shown in the example below.
# Open file in current directory
fid = open('input.txt', 'r')
# Open file in another directory
fid = open('C:/Users/input.txt', 'r')
Basic methods for reading and writing to files
This section will display some basic functions for reading and writing to files. To not spend to much space on simple functions, we recommend you to read the documentation by docs.python.orgfor more details.
input.txt
Line 1
Line 2
Last line
Example code
with open('input.txt','r') as fid:
print('\nExample 1:')
print(fid.read()) # Reads the whole file
with open('input.txt','r') as fid:
print('\nExample 2:')
print(fid.readline()) # Reads a single line
with open('input.txt','r') as fid:
print('\nExample 3:')
print(fid.readlines()) # Reads the whole file as a list
with open('input.txt','r') as fid:
print('\nExample 4:')
print(fid.read(3)) # Reads 3 letters
with open('input.txt','r') as fid:
print('\nExample 5:')
for line in fid:
print(line, end='') # Reads lines using a loop.
# This is a memory efficient, fast and simple method.
Output of example code
Example 1:
Line 1
Line 2
Last line
Example 2:
Line 1
Example 3:
['Line 1\n', 'Line 2\n', 'Last line']
Example 4:
Lin
Example 5:
Line 1
Line 2
Last line
Example code
with open('input.txt','a') as fid:
fid.write('\nExample 1\n')
fid.write('Write simple text or numbers converted to strings\n')
fid.write(str(5))
with open('input.txt','a') as fid:
fid.write('\nExample 2\n')
arr = ['Array element 1', 'Array element 2']
fid.writelines(arr)
Input.txt (after writing)
Example 1
Write simple text or numbers converted to strings
5
Example 2
Array element 1Array element 2