Azad Rasul
SmartRS

SmartRS

10- Python file handling

Azad Rasul's photo
Azad Rasul
·Jun 27, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Python has several functions for creating, reading, updating, and deleting files.

open() function

For working with files the function is: open(fileName, mode) There are four different modes for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

Assume we have a txt file named data in your directory folder.

read() mode

file = open('data.txt', 'r')

Print every line in the file

for each in file:
    print (each)

# This is for testing!

write() mode

file = open('data.txt','w')
file.write("The write command allows us to write in a particular file. ")
file.close()

Open the file again:

file = open('data.txt', 'r')
print(file.read())
# The write commandIt allows us to write in a particular file.

append() mode

file = open('data.txt','a')
file.write("This will add this sentence.")
file.close()

Open the file:

file = open('data.txt', 'r')
print(file.read())
# The write commandIt allows us to write in a particular file. This will add this sentence.

If you like the content, please SUBSCRIBE to my channel for the future content

Did you find this article valuable?

Support Azad Rasul by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this