| by Arround The Web | No comments

Python File Handling

The file is a location on disk that is used to store information and file handling is an approach for managing files and performing various functions on it. In Python, different modules are available for managing several types of files such as text, binary, CSV, JSON, and more. This write-up will present you with a complete overview of Python file handling via the below contents:

What is Python File Handling?

How to Open a File in Python?

How to Create/Construct a File in Python?

How to Append the File in Python?

Exception Handling in Files

Python File Methods

Conclusion

What is Python File Handling?

Python file handling is the process of using Python to create, read, write, and manipulate files. Python supports a number of built-in methods that are utilized for file-handling operations. By using these methods, it is easier to work with files in different modes such as read, append, write, or create.

Python files are cross-platform, user-friendly, and versatile. However, they can also retrieve an error if the file is not present, or the code is not well-written.

The following/below are a few of the pros and cons of file handling in Python:

Pros Cons
Python file handling provides versatility. We can perform various operations on files with file handling. Python file handling can cause errors if there is an issue with the file.
Python file handling is user-friendly. It has a straightforward and instinctive interface that makes it easy to use. While working with complex file formats or operations, it can be complex.
Python file handling works on different platforms (e.g., Windows, Mac, Linux). Python file-handling operations can be slower while dealing with large operations.

 

How to Open a File in Python?

In Python, the “open()” function is used to open a particular file. This function opens or creates the file if not present based on different modes.

Syntax

f = open(filename, mode)

 

Parameters

In the above syntax:

  • The “filename” parameter represents the file name.
  • The “mode” parameter represents the modes of operation that need to be performed on the file after opening such as writing, reading, or appending.

Return Value

File object.

Now, let’s look at various modes of Python file handling:

Modes Descriptions
“r” – Read Open a file for reading
“r+” – Read and Write It is employed to read and write to the file.
“w” – Write Open the file for writing.
“w+” – Write and Read It is used to write and read the file data.
“a” – Append Open the file for appending/adding.
“a+” – Append and Read It is used to append and read the file data.
“x” – Create Creates the Particular File and if the file is present it will retrieve an error.

Opening and Printing File Data Using “open()” and “for” Loop

To open the file “example.txt” the “open()” function takes the file name and the mode “r” as an argument. After opening the file the “for” loop iterates over the file object and displays the content of the file:

f1 = open('example1.txt', 'r')
for i in f1:
    print(i)

 

The content of the file is shown below:

Displaying File Data Using read() Method

We can also display the file content using the “read()” method. First, we opened the file in read mode via the “open()” function. Next, we read the file utilizing the “read()” method. Use the below code to display the file data:

f1 = open('example1.txt', 'r')
print(f1.read())

 

The content of the file is shown below:

Read File Using with Statement

The “with” statement is utilized in the error/exception handling technique. It simplifies the file management and makes our code more readable and cleaner. In the below code, we open the file “example.txt” and store it in the object “f1”. Next, the object is used with the “read()” method to read the file content and display it using the “print()” method. Take this code as a practical demonstration:

with open("example1.txt") as f1:
    d = f1.read()
print(d)

 

Here is the output:

Read File With a Certain Number of Characters

We can read the specified file and retrieve the specified number of characters using the “file.read()” method. This method takes the “15” integer value as an argument and retrieves the first 15 characters from the file.

f1 = open("example1.txt", "r")
print (f1.read(15))

 

The below output displays the first 15 characters of the file:

Read a File Using readline() and readlines() Methods

The “readline()” method is employed to read the line-by-line content of the specified file. While the “readlines()” method reads all the files at once and displays them using the list as an element value. Let’s take this file as an example:

Here, in this code, we open the file and read the first file line utilizing the readline() method:

f1 = open('example1.txt', 'r')
print(f1.readline())

 

The output will look like this:

Next, we use the same file and read it using the “readlines()” method. This method reads all the files and retrieves the output:

f1 = open('example1.txt', 'r')
print(f1.readlines())

 

The list containing all the files has been retrieved to the output:

Splitting the Data While Reading a File

We can also execute different operations on the file data while reading the file. For example, let’s read the file “example.txt” with multiple lines. After reading the file, use the for loop and split the line using the “split()” method.

with open("example1.txt", "r") as f1:
    d = f1.readlines()
    for line in d:
        print(line.split())

 

All multiple liens of the file have been retrieved to the new list:

How to Create a File in Python?

To create a file the “open()” function takes the filename and the “w” mode as an argument. This mode specifies the function that opens or constructs a file for writing. Let us take a look at the following example to create and write the file:

Create and Write to a File

Here, first, open the file in writing mode using the “open()” function. Next, the “write()” method is used to write the string data/content to the particular file. We can utilize the write() method to write/input the strings. In the end, the file is close to making changes.

f1 = open('example1.txt','w')
f1.write("Hello! Welcome to Python Guide")
f1.write("and Linux Guide")
f1.close()

 

The below snippet shows the file content:

Using writelines() Method

To write multiple lines simultaneously, you can utilize the “writelines()” method. Here, below, we can employ the open() function to launch/open the file in write mode. Next, the list contains multiple lines of data separated by element value. After that, we can write all the lines using the “writelines()” method.

f1 = open("example1.txt","w")
L = ["Welcome to Python \n","Linux \n","Guide \n"]
f1.write("Linuxhint \n")
f1.writelines(L)
f1.close()

 

The file has been created with multiple lines of data:

Using with Statement

Similarly, we can also use the “with” statement along with the open() function to create the file. In this way, we eliminate the need to close the file. The “with” statement shuts the file automatically after performing the operation of writing data.

with open("example1.txt", "w") as f1:
    f1.write("Welcome to Python Guide")

 

The file is created:

How to Append the File in Python?

Sometimes, we do not need to overwrite or create a new file for writing new data. We can append the file data by employing the file append mode. For this, first, we open the file in “a” append mode. Next, the “write()” method is utilized to write the strings to the file and closes utilizing the close() method.

f1 = open('example1.txt', 'a')
f1.write("Welcome to Linux Guide")
f1.close()

 

The new strings data has been appended:

Exception Handling in Files

To manage the exception in files the “try” and “except” block is utilized in Python. For example, if you open a file but an error occurs, then the except block is executed and displays the specified data or closes the file. Here is the code that demonstrates the exception handling:

try:
    f1 = open("example1.txt", "r")
    print(f1.read())

except:
    f1.close()

 

The above code retrieves this:

Python File Methods

We can also perform multiple operations on Python file data using different file methods. Some of the methods are listed in the table below.:

Method Descriptions
close() Closes the open file.
isatty() Retrieve True if the file stream is interactive/connected.
seekable() Retrieve True if the file stream keeps random access.
readable() Retrieve True if the program runs in the terminal.
tell() Retrieve the file object’s current position as an integer.
writable() Check if the file object can be writable.
detach() Separate and retrieve the TextIOBase from the binary buffer.
fileno() Retrieve the file integer descriptor.
truncate() Modifies the file object to size bytes.
seek() Changes the position of the file to bytes offset.
flush() Flushes the write buffer of the file stream.

Conclusion

Files in Python are essential components that are utilized to store/keep and modify data. In Python, various built-in functions and modules are utilized to execute various operations on multiple types of files. File Handling is the approach of utilizing Python for dealing with files. We use file-handling methods to create, read, or write files in Python. This article covers how to work with files in Python utilizing numerous examples.

Share Button

Source: linuxhint.com

Leave a Reply