Getting information to and out of a file is a very important aspect of programming.
Some good examples are for games that keep track of High Scores. The High Score and name of the player can be kept in a file. When a player starts the game, the program loads the list and stores it in memory. When the user exits the game, the program saves the information back to the file.
File Modes
When accessing files, you have the choice of two variations of three types of access. This makes six modes of access.
Let's look at the three types of access first:
Using write access will create a new file if it does not exist. If the file exists, then the content is erased.
Appending to a file lets you change the contents that already exist and adds new data to the end of the file. If the file doesn't exist, then a new one will be created.
Each of these modes has two variations. The main variations are listed above, the 'r' mode is the only one that allows reading of the file. Using the normal write (w) and append (a) mode does not allow reading of the file.
The other variation has the same mode value, but contains a plus (+) sign. It simply allows reading and writing together:
No matter the mode in which you are opening a file, there is a proper order to handling the file.
There are three steps:
File I/O Commands
The first step is to open the file. The command is:
You can specify any variable, other than 'file1', to hold the pointer to the file.
The path needs to be an absolute path, starting from the root (/) folder. Do not use a tilde (~) for a shortcut to your Home folder.
If you are using Read mode, then you do not need to specify the mode. The Read mode is default. It is best practice to always specify the mode.
To read a file, use the 'read' method:
Any variable name can be used, but in this case, the contents of 'file1' are placed into the variable 'file_contents'. It is possible to access a single line at a time. Let's look at the other modes before we get to that.
To write to an open file, we simply use the command:
Be sure you have opened the file in a mode that allows writing. The command will write one line at a time. You can use variables instead of a literal to write data to a file:
For multiple lines:
Without the line breaks (\n), all output will end up on one line in the file.
To append information in a file, you open the file in append (a) mode and write to it as normal. Any data entered goes to the end of the file. If you performed the last set of code, to write three lines, do:
Change your filename and path as you need. After opening the file in append mode, the new file should be:
The first three lines were not erased as a file was done in write mode.
Hopefully, you ran the code above, and we will cover accessing individual lines from this file.
There are multiple methods to access lines of code. We will go over two of them.
The first is using the 'linecache' command. The entire file is read into memory, so an extensive file can use up resources. Let me give the code and then go over the code:
Here, we use the file '/home/jarret/test.txt' and get out the fifth line and place it into the variable 'line'.
If you do not want to import code and keep the entire file in memory, then you can use the code:
Here, we open the file for reading. The find lines are set up as the line numbers we want minus 1. The first line is 0 and not 1. So, I want lines 1, 3 and 6. We are setting 'lines' to nothing since any found lines are going in this variable.
The 'enumerate(file)' is a line-by-line access by counting each line. We then pull out each line that is listed in 'find_lines'. The 'strip' method removes any white spaces, including carriage returns (/n) and spaces.
Conclusion
This should get you started to access external files.
Be sure to try each mode and see what you can do with each one.
Some good examples are for games that keep track of High Scores. The High Score and name of the player can be kept in a file. When a player starts the game, the program loads the list and stores it in memory. When the user exits the game, the program saves the information back to the file.
File Modes
When accessing files, you have the choice of two variations of three types of access. This makes six modes of access.
Let's look at the three types of access first:
- r - read access
- w - write access (files are created or erased and started fresh)
- a - append access - write access (file is added to from the end)
Using write access will create a new file if it does not exist. If the file exists, then the content is erased.
Appending to a file lets you change the contents that already exist and adds new data to the end of the file. If the file doesn't exist, then a new one will be created.
Each of these modes has two variations. The main variations are listed above, the 'r' mode is the only one that allows reading of the file. Using the normal write (w) and append (a) mode does not allow reading of the file.
The other variation has the same mode value, but contains a plus (+) sign. It simply allows reading and writing together:
- r+ - read and write
- w+ - write and read
- a+ - write and read appending information
No matter the mode in which you are opening a file, there is a proper order to handling the file.
There are three steps:
- Open the file
- Read/Write/Append (depending on the mode)
- Close the file
File I/O Commands
The first step is to open the file. The command is:
Code:
file1 = open("</path/file-name>", "<mode>")
You can specify any variable, other than 'file1', to hold the pointer to the file.
The path needs to be an absolute path, starting from the root (/) folder. Do not use a tilde (~) for a shortcut to your Home folder.
If you are using Read mode, then you do not need to specify the mode. The Read mode is default. It is best practice to always specify the mode.
To read a file, use the 'read' method:
Code:
file_contents = file1.read()
Any variable name can be used, but in this case, the contents of 'file1' are placed into the variable 'file_contents'. It is possible to access a single line at a time. Let's look at the other modes before we get to that.
To write to an open file, we simply use the command:
Code:
file1.write("contents-to-write")
Be sure you have opened the file in a mode that allows writing. The command will write one line at a time. You can use variables instead of a literal to write data to a file:
Code:
file1.write(variable1)
For multiple lines:
Code:
file1.write("Line 1\n")
Code:
file1.write("Line 2\n")
Code:
file1.write("Line 3\n")
Without the line breaks (\n), all output will end up on one line in the file.
To append information in a file, you open the file in append (a) mode and write to it as normal. Any data entered goes to the end of the file. If you performed the last set of code, to write three lines, do:
Code:
file1 = open("/home/jarret/test.txt","a")
file1.write("Line 4\n")
file1.write("Line 5\n")
file1.write("Line 6\n")
file1.close()
Change your filename and path as you need. After opening the file in append mode, the new file should be:
Code:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
The first three lines were not erased as a file was done in write mode.
Hopefully, you ran the code above, and we will cover accessing individual lines from this file.
There are multiple methods to access lines of code. We will go over two of them.
The first is using the 'linecache' command. The entire file is read into memory, so an extensive file can use up resources. Let me give the code and then go over the code:
Code:
import linecache
line = linecache.getline("/home/jarret/test.txt",5)
print (line)
Here, we use the file '/home/jarret/test.txt' and get out the fifth line and place it into the variable 'line'.
If you do not want to import code and keep the entire file in memory, then you can use the code:
Code:
file = open("/home/jarret/test.txt",'r')
find_lines = [1-1,3-1,6-1]
lines = []
for i, line in enumerate(file):
if i in find_lines:
lines.append(line.strip())
print (lines)
file.close()
Here, we open the file for reading. The find lines are set up as the line numbers we want minus 1. The first line is 0 and not 1. So, I want lines 1, 3 and 6. We are setting 'lines' to nothing since any found lines are going in this variable.
The 'enumerate(file)' is a line-by-line access by counting each line. We then pull out each line that is listed in 'find_lines'. The 'strip' method removes any white spaces, including carriage returns (/n) and spaces.
Conclusion
This should get you started to access external files.
Be sure to try each mode and see what you can do with each one.