Updated March 20, 2023
Introduction to Python File Methods
File methods are the methods used for manipulating the files and the contents of files in any specific system. In python, there are specific pre-defined methods for working on the files and contents, such as open(), read(), readline(), next(), write(), writelines(), truncate(), seek() and close(). Open(), as the name says, used for open function, which along with other parameters like r, w, a, etc., expands the scope further. Similarly, write() can be combined with few parameters like r, a and w.
Python File Methods and File Objects
A file object is a way to access, use and manipulate user-accessible files. Let’s discuss some methods first to read files:
1. Open()
This function facilitates the user to open a file from a particular location and with a specific access mode.
Syntax:
open(address,access_mode)
“address” is your local system address where the file resides, and access mode is like: read-only, write-only, read and write both, etc.
List of All Modes:
- r: This mode opens a file in read-only form
- w: This mode opens a file in the write-only form
- r+: This mode opens a file in both reads and writes form
- w+: This mode opens a file in both write and read
- a: This mode opens a file for appending purpose
- a+: This mode opens a file for both appending as well as for reading
Example:
2. Read()
This function facilitates reading the full file in the form of a string. However, one can restrict the reading to a certain limit by specifying the size in this function like read(size).
Example:
Let’s see example through small code,
f = open("C:/Users/Test/desktop/Hello.txt", "r")
print(f.read())
ff = open("C:/Users/Test/desktop/Hello.txt", "r")
print(ff.read(5))
Output:
3. Readline()
This helps the user reading only the first line of the file or reading line until it meets an EOF character in the file. Suppose EOF is met at first, then an empty string will be returned.
Example:
f = open("C:/Users/Test/desktop/Hello.txt", "r")
print(f.read())
ff = open("C:/Users/Test/desktop/Hello.txt", "r")
print(ff.readline())
Output:
As one can see, out of all three lines present in the file, the readline has printed only the first line.
4. Next()
file.next is helpful while iterating a file through a loop. Every time it’s been called, it takes the next line.
Example:
Our file “Hello.txt” has 3 lines shown below,
Code:
ff = open("C:/Users/Test/desktop/Hello.txt", "r")
print(ff.next())
print(ff.next())
Output:
5. Write()
file.write() function is used to write the content in the output file.
Example:
As one can notice, a parameter is specified, i.e. “a”. Here it means append to the content to this file. If the file exists, it will write further. If the file doesn’t exist, it will be created and then written. These three types of parameters that can be used here:
- “x”: This is for creating a file. If the file exists with that name, an error will be thrown.
- “a”: This is for appending. If a file doesn’t exist, it will create that file.
- “w”: This will create that file if the file doesn’t exist and then write to it.
6. writelines()
Like the way readlines used to read string line by line, in iteration form. Similar way writelines is used to write string line if that’s in an iterable object form.
Code:
f = open("sample_EDUCBA.txt","w+")
iter_seq = ["This is good platform\n", "Datascience is buzzword"]
line = f.writelines( iter_seq )
f.close()
Output:
In the python console,
The generated file is,
7. truncate()
As the name suggests, this helps you shorten the file by chopping it off from anywhere required by the user.
Example: We have an input file,
Code:
ff = open("C:/Users/Test/desktop/sample_EDUCBA.txt", "r+")
print(ff.read())
ff = open("C:/Users/Test/desktop/sample_EDUCBA.txt", "w+")
ff.truncate()
ff = open("C:/Users/Test/desktop/sample_EDUCBA.txt", "r+")
print(ff.read())
Output:
Step1:
Step 2:
As one can notice, after getting truncated, there nothing printed on the console.
8. Seek()
This function helps users to set the offset position. By default, the value is 0. This is very useful when someone wants to adjust the position of the reading and writing pointer.
Example:
ff = open("C:/Users/i505860/sample_EDUCBA.txt", "r+")
ff.seek(0)
print(ff.readline())
ff = open("C:/Users/i505860/sample_EDUCBA.txt", "r+")
ff.seek(3)
print(ff.readline())
Output:
Step1:
Step2:
9. Close()
This function closes the file. A file, once it gets closed, can no more be used for reading or writing. File object created in reference to one file gets automatically closed when the same file object is assigned with another file; in python, it’s always good to close the file after use. A close function might throw an error in some situations where one running out of disk space.
Example:
f = open("sample_EDUCBA.txt","w+")
iter_seq1 = ["This is good platform\n", "Datascience is buzzword"]
line = f.writelines( iter_seq1 )
f.close()
iter_seq2 = ["Analytics Insights\n", "Machine Learning"]
f.writelines( iter_seq2 )
Output:
As one can notice, file object got created and written with some lines like:
“This is good platform\n”, “Data science is the buzzword.”
The file then closed. However, we tried writing a few more sentences like:
“Analytics Insights\n”, “Machine Learning”
Which resulted in “ValueError”.
Conclusion
The above-covered functions are important and easy to use functions in file handling with python. They are easy to grasp and use in a python programming language. Keeping these nitty-gritty functions handy is always a good practice while writing production-level code. Beginners can get a good grip over these by practicing them all.
Recommended Articles
This is a guide to Python File Methods. Here we discuss different python file methods along with the examples and their implementation. You may also look at the following articles to learn more –