You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 10 Next »



Page content

Introduction

Open and close files

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.

CharacterMeaning
'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.

Close file - Method 1
# 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"
Close file - Method 2
# 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"
Close file - Method 3
# 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 file
# 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


Textfile [.txt]




  • No labels