DEV Community

Dr. Azad Rasul
Dr. Azad Rasul

Posted on

10- How to handle files in Python?

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')
Enter fullscreen mode Exit fullscreen mode

Print every line in the file

for each in file:
    print (each)

# This is for testing!
Enter fullscreen mode Exit fullscreen mode

write() mode

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

Open the file again:

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

append() mode

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

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.
Enter fullscreen mode Exit fullscreen mode

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

To get full video tutorial and certificate, please, enroll in the course through this link: https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7

Top comments (0)