In Python, there are several operations like create, read, write, and delete, these help you in handling files effectively. In this article, we will take a closer look at some of the common file operations that you can perform in Python, such as opening a file, reading data from a file, writing data to a file, and more. Understanding file operations are necessary when you are learning Python.
Operations of Handling Files in Python
read | |
write or save | |
append | |
delete | |
check |
Now, let’s jump into learning file handling in Python using operations like opening a file, reading a file, writing into it, closing, renaming, deleting, and other file methods.
1. Opening a file
Whether you read or write to a file, you need to first open the file. You can open a file using the open()
function. The open()
function takes two arguments: the file name and the mode you want to open the file.
Syntax of the open()
function:
# Open file
file = open("filename", "mode")
The filename
argument should be a string that specifies the name of the file you want to open.
The mode parameter specifies the purpose of opening the file. There are several modes available for opening a file, including:
"r"
: read mode (default)"w"
: write mode"a"
: append mode"x"
: create mode"b"
: binary mode"t"
: text mode (default)"r+"
: read and write mode
1.1 Open File in Read Mode
To open a file in read mode, you can pass "r"
as the second argument to the open()
function. Once you’ve opened a file in read mode, you can use methods like read()
, readline()
, and readlines()
to read the contents of the file.
# Open file
file = open("file.txt", "r")
# Read the data
content = file.read()
# Print the content
print(content)
# Close the file
file.close()
1.2 Open File in Append Mode
Appending to a file means adding new content to the end of an existing file, without overwriting the existing contents.
# Open file in append mode
file = open("file.txt", "a")
# Write new data
file.write("This is some new content!\n")
file.close()
2. Reading data from a file
To read data from a file in Python, you need to first open the file in read mode using the open()
function, as we discussed earlier. Once you’ve opened the file, there are several methods you can use to read its contents.
See the following different file operations for reading data from a file.
Method | Description |
---|---|
read() | Reads the entire contents of a file into a single string. |
readline() | Reads a single line of a file at a time. |
readlines() | Reads all the lines of a file into a list of strings. |
As you can see in the table, If you want to read the entire contents of a file into a single string, you can use the read()
method.
# Open file
file = open("file.txt", "r")
# Read the entire file
content = file.read()
print(content)
# Close file
file.close()
However, If you want to read a file line by line, you can use the readline()
method.
# read filrst line
line = file.readline()
# read other lines in while loop
while line:
print(line)
line = file.readline()
# Close the file
file.close()
Similarly, we can use the readlines()
method to read all lines at once:
# Read all lines
lines = file.readlines()
for line in lines:
print(line)
3. Writing data to a file
To write data to a file in Python, you need to first open the file in write mode using the open()
function. Once you’ve opened the file, you can write data to it using the write()
method.
If you want to create a new file and write some content to it, you can open the file in write mode using "w"
.
# Create new file and write to it
file = open("new_file.txt", "w")
file.write("This is some new content!\n")
file.close()
However, if you have already a file, then you might need to open it in append mode using the a
as parameter.
# Open to an existing file
file = open("existing_file.txt", "a")
file.write("This is some new content!\n")
file.close()
4. Creating a file
Python makes it easier for us to create files implicitly when reading or writing to a file. However, if you want to explicitly create a new file in Python, you can use the open()
function with write mode ("w"
) or create mode ("x"
).
# Below code will create a new file
try:
file = open("new_file.txt", "x")
except FileExistsError:
print("File already exists!")
5. Deleting a file
Deleting files is another operation on a file. To delete a file in Python, you can use the os.remove() method. The os module is a Python built-in module that interacts with the operating system.
See the below example:
import os
if os.path.exists("file_to_delete.txt"):
os.remove("file_to_delete.txt")
print("File deleted.")
else:
print("The file does not exist.")
6. Renaming a file
You can use the os.rename()
method for renaming a file in Python. This method takes two arguments: the original name of the file and the new name that you want to give it. If the file exists, it will be renamed with the new name you provide. If the file does not exist, a FileNotFoundError
will be raised.
Syntax:
# Syntax
os.rename(src, dst)
See the following example:
import os
if os.path.exists("old_file.txt"):
os.rename("old_file.txt", "new_file.txt")
print("File renamed.")
else:
print("The file does not exist.")
7. Most Used Examples of File Handling
Following are the most used in-depth explanations of each file-handling operation with examples.
- How to Append to a File in Python
- Extract Extension from filename in Python
- Python Read a File line-by-line into a List?
- Import Files from Different Folder in Python
- Python Find Current Directory and File Directory
- How to delete file or folder in Python?
- Python List all Files in a Directory
- How to Copy Files in Python
- Python Check if File Exists
- How to Print to stderr in Python?
- How do you read from stdin in Python?
8. Summary and Conclusion
We have discussed different file-handling operations that are essential aspects of Python programming. I hope you know some of the most common file operations in Python, including opening a file, reading data from a file, writing data to a file, appending data to a file, creating a file, deleting a file, and renaming a file.
Happy Coding!