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.
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.
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.org for more details.
Text file [.txt]
Text files are a very common file for storing information, mostly due to their simplicity. Although text files can be interpreted as a general level of description (compared to binary files), or include multiple suffixes for language-specific text files (e.g. .mat and .py), we will in this section only consider the suffix .txt. As seen in the introduction, several methods for working with text files have already been established. However, most of these are not considered effective, especially when introducing large quantitives of data through e.g. matrices.
Using NumPy
To read all about input and output in NumPy, visit the NumPy documentation. As for our example information (introduced at the top of this page), we will first aim to write it to a file. For this, we will be using the function numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='n', header='', footer='', comments='# ', encoding=None)
. At first, this may seem like a lot of parameters for one simple function, but hopefully, you will soon see it as a pure benefit.
import numpy as np mat = np.array([[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 10, 0]]) with open('output.txt', 'w') as fid: # We will through all parameters here, but keep in mind that you don't have to include them if you're just keeping the default np.savetxt(fid, # 'fname' refers to the id of our file; fid mat, # 'X' is our matrix/array to be saved to the file '%d', # 'fmt' refers to the format of our data, in this case, we want to store it as integers,'d' '\t', # 'delimiter' is the string or character separating the columns of our matrix, e.g. '\t', meaning the tab delimiter '\n', # 'newline' is the string or character spearating the lines. '\n' is the newline specifier, which is default 'Coordinates\nx\ty\tz\t', # In the 'header' we can add the information we want to save above our data # Note that we could also have done this using some lines of 'fid.write()' # , but for our short text, this is easier '', # 'footer' is similar to the header of the file, but located below the data '', # 'comments' is as expected, comments, and is prepended to the header and footer using '#' None # Choose 'encoding' for output file. 'None' is default ) # --- # output.txt will now look like this: Coordinates x y z 0 0 0 10 0 0 10 10 0 0 10 0