Python File Handling

Files are named locations on disk to store related information. Images, text, video, audio, scripts etc. are the may types of files. In Python there are 2 types of files: (i) Binary (ii) Text

Python has several functions for creating, reading, writing, updating and deleting files. Hence, in Python, a file operation takes place in the following order:

(i) Open a file

(ii) Read or write(any operation)

(iii) Close the file

Working of open( ) function

file = open("samplefile.txt")      # equivalent to 'r' or 'rt'
file = open("samplefile.txt",'w') # write in text mode
file = open("img.bmp",'r+b') # read and write in binary mode
# when working with files in text mode, it is highly recommended to specify the encoding type.
file = open("samplefile.txt", mode='r', encoding='utf-8')

We use open() function in Python to open a file , open( ) returns a file object, and mostly used with two arguments: open(filename, mode). There are different kinds of mode, that python provides and how files can be opened i.e. read, write and append.

"r" - Read - Default. 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

"r+" -opens the file for both reading and writing.

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Working of read() mode

To read a file in python, we must open the file in reading mode. There are various methods to read a file(according to our need).

file =open("samplefile.txt",'r',encoding='utf-8') #open in read mode
print(file.read()) # read the complete file
print(file.readline()) # read 1 line
print(file.read(size)) # read some quantity of data upto(size)

read() method returns the newline as ‘\n’. once the file is reached, we get an empty string .

Creating a file using write() mode

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

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

file = open("samplefile.txt",'a') #open in read mode
print(file.write('This line is added to existing file'))
file.close() # we must close the file
file = open("samplefile.txt",'w') #this will overwrite the content
file.write('all contents have been deleted')
file.write('nxt line')
file.writelines('multiple lines')
file.close() # we must close the file

To create a new file in Python, use the open() method in with following mode :

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

file = open("samplefile.txt",'w')

Closing a File

When you’re done working, you can use the "file.close()" command to end things. we should always close our files, in some cases, due to buffering, changes made to a file may not show until we close the file.

Using write along with with() function

It is good practice to use the "with" keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. It automatically close the file.

That’s all for this blog. Thanks for reading.🙌

Refrences:

https://docs.python.org/3/tutorial/inputoutput.html

--

--

--

The price of “anything” is the amount of “time”, U xchange for it. Education | Technology | Data Science | Statistics | History

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Migrating WordPress Website To Lightsail On AWS

Migrating WordPress Website To Lightsail On AWS - Part 4

#freestockphoto (Monday 16th 02PM)

Primer guide to Android reverse engineering: apkdigger

The Complete Python Developer in 2022 — Zero to Mastery

2 Easy Methods to Auto Apply Watermark to New Outlook Emails

Add Watermark to a New Email

Canary Release in Kubernetes for Java Applications by Leveraging Spring Boot Annotations

Lawyers in Utah

lawyers in utah

Automate Start Azure VM — Using Microsoft Teams, Office 365 Forms and Azure LogicApp

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abu Qais

Abu Qais

The price of “anything” is the amount of “time”, U xchange for it. Education | Technology | Data Science | Statistics | History

More from Medium

Unit Testing In Python

Python pushed with Git-hub!

Push-up Counter Using Python(With Mediapipe)

Tkinter: python’s standard GUI