In this Python tutorial, we will discuss file methods in Python with examples to know and clear the concept about the file methods.
There are multiple methods for handling the file in Python, which are shown below:
- Python file method open()
- Python file method read()
- Python file method readline()
- Python file method write()
- Python file method writelines()
- Python file method close()
- Python file method seek()
- Python file method tell()
- Python file method flush()
Python File Methods
Python provides a variety of methods that can be used to work with files, including opening, reading, writing, and closing files.
These methods make it easy to interact with files in your Python programs and can be used to perform a wide range of file-related operations, from basic reading and writing to more complex file manipulation tasks.
Method-1: Python file method open()
The open() function is used to open a file and returns a file object. It takes two arguments – the name of the file to be opened and the mode in which the file should be opened (e.g., “r” for reading, “w” for writing, and “a” for appending).
#Use the open() function to open a file called "examplefile.txt" in "append"
f = open("examplefile.txt", "a")
# Print the value of f
print(f)
The above code opens a file called “examplefile.txt” in “append” mode using the open() function.
- “Append” mode allows the program to add new data to the end of the existing data in the file, rather than overwriting it. The resulting file object is assigned to the variable
f
. - Finally, the code prints the value of f, which represents the file object. The output will be a representation of the file object that shows the file name, the mode in which the file was opened, and the file encoding.
Output: <_io.TextIOWrapper name='examplefile.txt' mode='a' encoding='UTF-8'>
Read: Get current directory Python
Method-2: Python file method read()
The read() method is used to read the contents of a file. It takes an optional argument that specifies the number of bytes to be read. If no argument is provided, it reads the entire file.
# Use the open() function to open a file called "examplefile.txt" in "read" mode
f = open("examplefile.txt", "r")
# Use the read() method to read the contents of the file and print them to the console
print(f.read())
The above code opens a file called “examplefile.txt” in “read” mode using the open() function. “Read” mode allows the program to read the contents of the file.
- The resulting file object is assigned to the variable f. The read() method is then used to read the contents of the file and print them to the console. The output will be the contents of “examplefile.txt”.
Read: Python copy file
Method-3: Python file method readline()
The readline() method is used to read a single line from a file. It reads the characters from the current position up to and including the next newline character.
# Use the open() function to open a file called "examplefile.txt" in "read" mode
f = open("examplefile.txt", "r")
# Use the readline() method to read the first line of the file and print it to the console
print(f.readline())
The above code opens a file called “examplefile.txt” in “read” mode using the open() function. “Read” mode allows the program to read the contents of the file.
- The resulting file object is assigned to the variable f. The readline() method is then used to read the first line of the file and print it to the console. The output will be the first line of “examplefile.txt”.
Output: Hello, welcome to this file
Read: Os change directory Python
Method-4: Python file method write()
The write() method is used to write data to a file. It takes a string as its argument and writes it to the file.
# Open a file named "file.txt" in write mode
file = open("file.txt", "w")
# Write the string "Hello, World welcome" to the file
file.write("Hello, World welcome")
# Close the file to free up system resources
file.close()
# Open the same file in read mode
file = open("file.txt", "r")
# Read the first line of the file and print it to the console
print(file.readline())
# Close the file to free up system resources
file.close()
The above code creates a file named “file.txt” in write mode using the open() function. It then writes the string “Hello, World welcome” to the file using the write() method.
- The file is then closed using the close() method to free up system resources.
- The file is then opened again in read mode using the open() function. The first line of the file is read using the readline() method, and it is printed to the console using the print() function.
- Finally, the file is closed again using the close() method to free up system resources.
Hello, World welcome to USA
Method-5: Python file method writelines()
The writelines() method is used to write a list of strings to a file. It takes a list of strings as its argument and writes each string to the file.
# Creates a list of two strings
lines = ["The population of United State is 33.19 crores", "The Population of Brazil is 21.43 crores"]
# Opens a file named example.txt in write mode
file = open("example.txt", "w")
# Writes the lines list into the file
file.writelines(lines)
# Closes the file
file.close()
# Opens the same file in read mode
file = open("example.txt", "r")
# Prints the first line of the file
print(file.readline())
The above code creates a list named lines that contains two strings. Each string describes the population of a specific country.
- Then, the code opens a file named “example.txt” in write mode using the open() function, writes the content of the lines list into the file using the writelines() method, and closes the file using the close() method.
- After that, the code opens the “example.txt” file in read mode using the open() function and reads the first line of the file using the readline() method. Finally, the code prints the first line of the file to the console.
Output: The population of United State is 33.19 croresThe Population of Brazil is 21.43 crores
Read: Python read a binary file
Method-6: Python file method close()
The close() method is used to close a file that has been opened using the open() method. It flushes any unwritten data to the file before closing it.
# Open the file "example.txt" in read mode
file = open("example.txt", "r")
# Read the entire content of the file and store it in the 'content' variable
content = file.read()
# Print the content of the file
print(content)
# Close the file
file.close()
The above code opens a file named example.txt in read mode using the open() function and assigns it to the variable file.
- Then, it reads the entire contents of the file using the read() method and assigns the content to the variable content. Finally, it prints the content of the file to the console using the print() function.
- After the content is printed, the file is closed using the close() method to free up system resources.
Method-7: Python file method seek()
The seek() method is used to move the file pointer to a specific position in the file. It takes an offset and a reference point as its arguments.
# This code opens the file "example.txt" in read-only mode
file = open("example.txt", "r")
# This code sets the position of the file object to 5, which means that the next read operation will start from the 6th character of the file.
file.seek(5)
# This code reads the remaining contents of the file, starting from the 6th character # to the end of the file, and assigns the contents to the variable "content".
# content = file.read()
# This code prints the value of the "content" variable, which contains the remaining
# contents of the file starting from the 6th character.
print(content)
# This code closes the file.
file.close()
The above code opens a file named “example.txt” in read mode using the open() function and assigns the file object to the variable file.
- The seek() function is called on the file object with an argument of 5, which moves the file pointer to the 6th byte in the file.
- The read() function is then called on the file object to read the remaining contents of the file starting from the 6th byte, and the returned contents are assigned to the variable content.
- Finally, the value of content is printed to the console using the print() function, and the file is closed using the close() method on the file object.
Output: opulation of United State is 33.19 crores
Read: File does not exist Python
Method-8: Python file method tell()
The tell() method is used to return the current position of the file pointer.
# Open a file named "example.txt" in read mode
file = open("example.txt", "r")
# Print the current position of the file pointer using tell()
print(file.tell())
# Read 5 characters from the file and print the current position of the file pointer again
content = file.read(5)
print(file.tell())
# Close the file
file.close()
The above code is opening a file named example.txt in read-only mode using the open() function and assigning the file object to the variable file.
- The print(file.tell()) statement returns the current position of the file pointer, which is initially set to 0.
- The file.seek(5) statement moves the file pointer to the 6th byte in the file, which is position 5 since the file pointer starts at position 0. The content = file.read(5) statement reads 5 bytes from the current position of the file pointer and assigns it to the variable content.
- The print(file.tell()) statement returns the current position of the file pointer, which is now 10 since we read 5 bytes starting from position 5.
- Finally, the file is closed using the file.close() statement.
Output: 0
5
Method-9: Python file method flush()
The flush() method is used to flush the internal buffer of a file object. It forces any unwritten data to be written to the file.
# Open a file named "example.txt" in write mode.
file = open("example.txt", "w")
# It writes the string "United States, USA" into the file.
file.write("United States, USA")
# The flush() method is called to immediately write the contents to the file.
file.flush()
The above code creates a file named “example.txt” in write mode using the open() function. The file is opened in write mode, which means that any existing content in the file will be overwritten.
- The write() function is then used to write the string “United States, USA” to the file. After writing to the file, the flush() function is called to force any buffered data to be written to the file immediately, ensuring that the data is written to the file and not just to a buffer.
Conclusion
In this Python tutorial, we have covered 9 methods of Python file with examples and how it works.
- Python file methods open()
- Python file methods read()
- Python file methods readline()
- Python file methods write()
- Python file methods writelines()
- Python file methods close()
- Python file methods seek()
- Python file methods tell()
- Python file methods flush()
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.