Opening and Closing of a File
To read data from a text file named “data.txt”, you need to use the “open” method that comes with official Python builds. Check the sample code below:
The first statement opens the “data.txt” file in “r” (read-only) mode. The “open” method accepts a filename and the mode for handling the file as arguments. Besides “r” mode, there are other modes as well that will be explained later. The code snippet above does not run any operations on the opened file. The “close” method is used to close the opened file cleanly so that memory can be freed and to avoid data corruption in the opened file that can happen sometimes if the file is not closed properly.
Instead of using the “open” method to handle opening and closing of files, you can combine it with “with” keyword and use “with open” statement.
The main advantage of using a “with open” statement is that the interpreter automatically closes the opened file safely when “with open” code block is parsed completely. Though garbage collector in Python automatically closes opened files after a while as per preset rules, “with open” statements ensure that file is cleanly closed as soon as the code block is finished to free up resources.
Reading Lines of a Text File
To read contents of a file, use the code sample below:
data = f.read()
For instance, if “data.txt” file has 1-10 numbers, each on a new line, you will get following output after running the above code:
The entire data dump of the “data.txt” file is stored in the “data” variable. If you want to read lines to a list, you can use following code samples:
data = f.readlines()
data = list(f)
Note that using above snippets may get you the “\n” (newline) character at the end of each element in the list. To remove these newline characters, you may have to loop through the list. You can both create a new list and strip newline characters by using following code instead:
with open('data.txt', 'r') as f:
for line in f:
Running the code above will get you following output:
Writing Data to an Opened File
To write data to a file being opened using the “with open” statement, you will have to supply a different opening mode as argument. Here are some of the modes:
- ‘a’ – used for appending data at the end of an opened file, creates new file if it doesn’t exist
- ‘w’ – erases contents of opened file and writes new data, creates new file if it doesn’t exist
- ‘r’ – read-only mode (default mode if no argument is supplied)
- ‘r+’ – used for both reading and writing (initial position is at the beginning of the file)
- ‘b’ – file is opened in binary mode (useful for non-text binary files), can be combined with other modes
- ‘a+’ – used for reading and appending, creates a new file if it doesn’t exist
- ‘w+’ – used for reading and writing, creates a new file if it doesn’t exist
Some code snippets using different modes to write data are listed below.
To write new content to a text file while erasing existing data, use the following sample:
After running the snippet above, 1-10 numbers in the “data.txt” file should be replaced by two new lines.
To add lines at the beginning of a text file, you need to use “seek” method to go back to the starting position of the file buffer:
data = f.read()
After running the snippet above, -1 and 0 numbers will be added to the top two lines in “data.txt” files.
To append data at the end of the file, use the following sample:
After running the snippet above, 11 and 12 numbers will be added at the end of the file.
Built-in classes and methods in Python provide a robust way to handle text files. With only a few lines of code you can manipulate existing data in a file as well as insert new lines.