Skip to content

File Operations in Python AlixaProDev Spark By {Examples}

  • by

In Python, you can easily create, read, write, and manipulate files using built-in functions and modules. 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.

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 in which 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 methods for reading data from a file:

MethodDescriptionread()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.Functions for reading file

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 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. Summary and Conclusion

We have discussed different file operations that are essential aspects of 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!

 In Python, you can easily create, read, write, and manipulate files using built-in functions and modules. 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.  Read More Python, Python Tutorial 

Leave a Reply

Your email address will not be published. Required fields are marked *