Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.




Panel
borderColor#dfe1e5
bgColor#eff9ff
borderWidth2
titlePage content

Table of Contents


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.

Code Block
languagepy
titleClosing file - Method 1
collapsetrue
# 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"


Code Block
languagepy
titleClosing file - Method 2
collapsetrue
# 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"


Code Block
languagepy
titleClosing file - Method 3
collapsetrue
# 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"


Code Block
languagepy
titleNot closing file
collapsetrue
# 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.

Code Block
languagepy
# 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.org for more details.

Expand
titleRead from files


Code Block
languagetext
titleinput.txt
Line 1
Line 2
Last line


Code Block
languagepy
titleExample 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(3))   # Reads at most n letters. 
							  # However, does not reads more than one line, even if n exceeds the length of the line.


with open('input.txt','r') as fid:
    print('\nExample 4:')
    print(fid.readlines())   # Reads the whole file as a list

with open('input.txt','r') as fid:
    print('\nExample 45:')
    print(fid.read(3))      # Reads 3 letters

with open('input.txt','r') as fid:
    print('\nExample 56:')
    for line in fid:
        print(line, end='') # Reads lines using a loop.
                            # This is a memory efficient, fast and simple method.


Code Block
languagepy
titleOutput of example code
Example 1:
Line 1
Line 2
Last line

Example 2:
Line 1


Example 3:
Lin

Example 4:
['Line 1\n', 'Line 2\n', 'Last line']

Example 45:
Lin

Example 56:
Line 1
Line 2
Last line



Expand
titleWrite to files


Code Block
languagepy
titleExample 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)


Code Block
languagepy
titleInput.txt (after writing)
Example 1
Write simple text or numbers converted to strings
5
Example 2
Array element 1Array element 2



Textfile [.txt]




BibTeX Display Table