A File can be defined as a named container that stores information in the computer system. There is a saying that states: “Everything in UNIX is a file”, and it is actually very true. Not only in UNIX systems, but also consider your windows PC: The shortcuts on your desktop or in the start menu are link files that point to the applications’ executables, your word documents, your excel sheets, and your favorite songs, all are files of different types. Even folders that are used as containers to store sub-folders and files are also files of a special type.
Computer programs need to read data from files, and may need to write output data to other files. This makes the capability of working with files a very important issue to a computer programmer.
In this article, we are going to learn how to work with Files in Python: how to open a file, read from a file, and how to write to a file.
To open a file for read or write operations, the built-in function open is used. The open function accepts two arguments:
First: A string, which is the name (and path) of the file to be opened.
Second: Also a string; the opening purpose (mode): either it is opened for read ‘r’, write ‘w’, append ‘a’, or both read and write ‘r+’.
The open function returns a file object, whose methods can be called for working with the file.
Reading the contents of a file
To read the contents of the file in hand, several read methods exist. The usage of these methods is quite straightforward.
Consider we have the following file, which is located under “G:\Python”
To open this file for reading:
To read the entire file and store it in a string:
To read the entire file and store it in a list of strings (each contains an individual line):
To read the contents of the file line by line:
In the following example we have a file that contains a set of numbers (each number in a separate line). We need a script that reads the numbers, calculates their total and average, and finally prints the results. The file to read is shown in the Figure 2.
Study the following script, and watch the results:
The script is self-explanatory, nut I would like to stress on several points:
- The readlines method returns a list whose elements contain individual file lines.
- The for loop can be used to loop on a list using the syntax:
- The eval function evaluates each element and returns the resulting value.
for loopvar in listname:
Creating and Writing to a File
To create a file, use the open function to open it for writing, and then write data to it.
First, we called the open function and passed to it a string that represents the path and name of the file to be created, followed by ‘w’ (write mode). The open function returned a File object that we would use to reference the file for the coming operations. Next, we have called the write method to write the string “Hello, I am a Python Programmer\n” to the file. Finally, the close method was called to close the file manually.
Appending to Files
To append some data to an existing file, use the open function with ‘a’ as the open mode.
After opening the file for appending, three lines have been written (appended) to the file. When finished with the file, the close method has been called to close it.
To verify that the new lines have been written to the file, simply open the file. The three lines should appear after the original content of the file.
Writing a List to File
A list of strings can be written to a file. If each individual element string contain a new line character at the end, each element will be written to a separate line.
A new file should be created, and have the above names added to it, one per line.
Opening a File for Both Reading and Writing
As mentioned in the introduction, a file can be opened for both reading and writing using the ‘r+’ as the second argument to the open function.
Consider the following example in which we are going to work with the newfile.txt which we created earlier in this article. We will open the file for reading and writing, read the file content to a string variable and print it. Next, we will write a string to the file, and finally, we finish by closing the file.
The ‘r+’ mode gave us the capability to read the contents of the file, and to write to the file.
Useful Attributes and Methods
The File Class has a number of useful attributes and methods. We have already investigated some of these methods (read, readlines, write, and writelines). Following are some other attributes and methods supported by this class:
The readable Method
The writable Method
The mode Attribute
The closed Attribute
* * * * * *
In this article, we have learned how to work with files. The capability to work with files is vital for the success of the computer developer. We have learned how to open a file for read, write, append, and both read and write.
I hope you find this article useful.