Azad Rasul
SmartRS

SmartRS

10- Python file handling

Azad Rasul's photo
Azad Rasul

Published on Jun 27, 2021

1 min read

Subscribe to my newsletter and never miss my upcoming articles

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.
 
Share this
Proudly part of