Operations on files in Python are vital for manipulating, analyzing, and storing data, as well as for reading and writing data to and from files. The basics of file operations in Python, including how to open, read, write, and manipulate files, as well as more advanced techniques for efficient file management, will be covered in this article. Explore the various types of operators in Python.
Why are File Operations in Python Important?
Working with files is a basic requirement when working with huge datasets for machine learning tasks. Python is one of the most used languages for data science; therefore, you should be familiar with all its file operations. Now, let’s explore a few Python file operations.
Opening a File using the open() function
To work with files in Python, you must first learn how to open files. To open files, use the open() function. Python’s open() method takes two parameters. The file name and entire path are the first, while the file open mode is the second.
The following are popular reading modes for files:
Reading Modes | Descriptions |
r | This mode indicates that the file is intended to be read-only. |
w | This option indicates that writing to the file will only be permitted. It will create a new file if the one with that name doesn’t exist. |
a | This mode indicates that the program’s output will be appended to the file’s earlier output. |
r+ | This option indicates that writing and reading of the file will be permitted. |
w+ | To read and write data. It will replace the current data. |
a+ | To obtain and append data from the file. It is not going to replace the current data. |
Moreover, you can append “b” to access the file in binary for the Windows operating system. This is a result of Windows’ ability to distinguish between ordinary text files and binary text files. Let’s say we put a text file called “file.txt” in the same directory as our code. It’s time to open the file. Nevertheless, the open(filename, mode) function returns a file object. You can continue with your task using that file object.
Example
text_file = open(‘file.txt’,’r’)
text_file2 = open(‘/home/imtiaz/file.txt’,’r’)
print(‘First Method’)
print(text_file)
print(‘Second Method’)
print(text_file2)
Output
First Method
Second Method
Suggested Article: How to Print in Python?
Reading and Writing Files in Python
Python provides many ways to read from and write to files, with each function exhibiting unique behavior. The file operations mode is one item to be aware of. You must open a file in read or write mode to read it. Python requires that the file be open in write mode to write to it. The following are a few Python functions that let you read and write to files:
Python Functions | Descriptions |
read() | This function retrieves a string after reading the full file. |
readline() | This function retrieves a string representation of the lines it reads from the file. If it is invoked the nth time, it retrieves line n. |
readlines() | This function yields a list with a single line from that file for each element. |
write() | This function creates a file with a predetermined character sequence. |
writelines() | This function outputs a string list. |
append() | Rather than overwriting the file, this function adds a string to it. |
Example
text_file = open(‘/Users/SLA/abc.txt’,’r’)
line_list = text_file.readlines();
for line in line_list:
print(line)
text_file.close() #don’t forget to close the file
Output
>>
========= RESTART: /Users/SLA/Desktop/read-file.py ====
Hi SLA
I am here
>>
Now that we understand how to read a file in Python, let’s use the writelines() function to execute a write operation.
Example
text_file = open(‘/Users/SLA/file.txt’,’w’)
word_list= []
for i in range (1, 5):
print(“Please enter data: “)
line = input() #take input
word_list.append(line)
text_file.writelines(word_list) #write 4 words to the file
text_file.close() #don’t forget to close the file
Output
>>>
========= RESTART: /Users/SLA/Desktop/write-file.py ======
Please enter data:
1
Please enter data:
2
Please enter data:
3
Please enter data:
4
>>>
Copying Files in Python using the shutil() method
Python’s shutil method can be used to copy files. With the help of this tool, we can move and copy files between different Python environments.
For example
import shutil
shutil.copy2(‘/Users/SLA/abc.txt’, ‘/Users/SLA/abc_copy2.txt’)
shutil.copyfile(‘/Users/SLA/abc.txt’, ‘/Users/SLA/abc_copyfile.txt’) #alternative way
print(“File Copy Done”)
Delete Files in Python with shutil.os.remove() method
Use the remove() function from the shutil module in Python to remove files from the file system. Let’s see how to execute a delete operation in Python.
import shutil
import os
shutil.os.remove(‘/Users/SLA/abc_copy2.txt’)
os.remove(‘/Users/SLA/abc_copy2.txt’)
Closing Files in Python using close() method
You must close any Python files you open after making any modifications to them. This eliminates the file from memory, saves whatever changes you’ve already made, and stops the application from reading or writing to the file again.
Syntax
fileobject.close()
Example
text_file = open(‘/Users/SLA/abc.txt’,’r’)
text_file.close()
If you use the with block, you can also avoid having to manually close files. The files are closed and become unreadable and unwritable as soon as the with block is run. Explore the top 20 Python projects for data science.
Python FileNotFoundError
When interacting with files in Python, it’s typical to encounter a FileNotFoundError. By giving whole file paths while creating the file object, it may be easily prevented.
File “/Users/SLA/Desktop/string1.py”, line 2, in <module>
text_file = open(‘/Users/SLA/Desktop/abc.txt’,’r’)
FileNotFoundError: [Errno 2] No such file or directory: ‘/Users/SLA/Desktop/abc.txt’
You only need to confirm that the path you provided for the file open method is accurate to resolve the FileNotFoundError.
Advantages of Python File Operations
The following are the advantages of Operations on Files in Python
Versatility: You can do a lot of different actions with files in Python, including creating, reading, writing, appending, renaming, and deleting them.
Flexibility: Working with many file types (text, binary, CSV, etc.) and performing various actions on files (read, write, append, etc.) makes file handling in Python extremely flexible.
User-friendly: It’s easy to create, read, and edit files with Python’s file management interface.
Cross-platform: Python routines for managing files are compatible and easily integrated with a variety of operating systems and platforms, including Windows, Mac, and Linux.
Disadvantages of Python File Operations
The limitations of operations on files in Python
Error-prone: Python file handling operations may be prone to mistakes, particularly if the code is poorly designed or the file system (such as file permissions, file locks, etc.) has problems.
Security risks: Managing files in Python may also give rise to security problems, particularly when the application allows user input that could be exploited to gain access to or alter confidential files on the system.
Complexity: Working with increasingly sophisticated file formats or operations in Python might make file handling more difficult. For files to be handled correctly and securely, careful attention to the coding is required.
Performance: Python’s operations on files can be slower than those of other programming languages, particularly when processing huge files or carrying out intricate tasks.
Implementations of Operations on File in Python
We will go over each of the previously seen principles in this example. In addition to that, we’ll also look at how to use the Python OS module’s remove() function to remove a file.
Example
import os
def create_file(filename):
try:
with open(filename, ‘w’) as f:
f.write(‘Hello, world!\n’)
print(“File ” + filename + ” created successfully.”)
except IOError:
print(“Error: could not create file ” + filename)
def read_file(filename):
try:
with open(filename, ‘r’) as f:
contents = f.read()
print(contents)
except IOError:
print(“Error: could not read file ” + filename)
def append_file(filename, text):
try:
with open(filename, ‘a’) as f:
f.write(text)
print(“Text appended to file ” + filename + ” successfully.”)
except IOError:
print(“Error: could not append to file ” + filename)
def rename_file(filename, new_filename):
try:
os.rename(filename, new_filename)
print(“File ” + filename + ” renamed to ” + new_filename + ” successfully.”)
except IOError:
print(“Error: could not rename file ” + filename)
def delete_file(filename):
try:
os.remove(filename)
print(“File ” + filename + ” deleted successfully.”)
except IOError:
print(“Error: could not delete file ” + filename)
if __name__ == ‘__main__’:
filename = “example.txt”
new_filename = “new_example.txt”
create_file(filename)
read_file(filename)
append_file(filename, “This is some additional text.\n”)
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
Output
File example.txt created successfully.
Hello, world!
Text appended to file example.txt successfully.
Hello, world!
This is some additional text.
File example.txt renamed to new_example.txt successfully.
Hello, world!
This is some additional text.
File new_example.txt deleted successfully.
Conclusion
Operations on files in Python are valuable tools for interacting with and modifying files inside Python programs. Python’s file handling is simple and easy to understand, unlike other programming languages. As said previously, it can save you a significant amount of time. Having said that, to increase the effectiveness and productivity of their work, one might attempt to investigate a few more file operations in Python. Enroll in our Python training in Chennai at Softlogic Systems and kick-start your promising career.