File Handling in Python

Python tutorial

Python Input and Output Operations

File Handling in Python

File handling in Python, Python open Function, Create a File using Python, Read a Text File, Write to an existing file, and Delete a File. Python Input and Output Operations.

Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files and Python treats file differently as text or binary.

open() function

We use open () function in Python to open a file in read or write mode. open () will return a file object, to return a file object we use open() function along with two arguments, that accepts file name and the mode, whether to read or write.

In Python, a file operation takes place in the following order.

Open a file
Read or write (perform operation)
Close the file

Syntax: open(filename, mode).

There are three kinds of mode, that Python provides and how files can be opened,

“r “, for reading.
“w”, for writing.
“a”, for appending.

“r+”, for both reading and writing

The mode argument is not mandatory. If not passed, then Python will assume it to be “r” by default.

File Handling Examples:

1) Read a File

The open() function returns a file object, which has a read() method for reading the content of the file:

Example

f = open(“sample.txt”, “r”)
print(f.read())

2) Read Only Parts of the File

Example
Return the 5 first characters of the file:

f = open(“sample.txt”, “r”)
print(f.read(5))

3) Read Lines

You can return one line by using the readline() method:

Example
Read one line of the file:

f = open(“sample.txt”, “r”)
print(f.readline())

4) Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

“a” – Append – will append to the end of the file

“w” – Write – will overwrite any existing content

Example

Open the file “sample.txt” and append content to the file:

f = open(“sample.txt”, “a”)
f.write(“Now the file has more content!”)
f.close()

#open and read the file after the appending:
f = open(“sample.txt”, “r”)
print(f.read())

5) Overwrite the content

Open the file “sample3.txt” and overwrite the content:

f = open(“sample3.txt”, “w”)
f.write(“Woops! I have deleted the content!”)
f.close()

#open and read the file after the appending:
f = open(“demofile3.txt”, “r”)
print(f.read())

6) Create a New File

To create a new file in Python, use the open() method, with one of the following parameters

“x” – Create – will create a file, returns an error if the file exist

Example

f = open(“myfile.txt”, “x”)

7) Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Example
#Remove the file “demofile.txt”:

import os
os.remove(“sample.txt”)

G C Reddy

G C Reddy, Working as a Software Testing Trainer in Hyderabad, India.

You may also like...

Leave a Reply

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