HOW TO HANDLE FILES IN PYTHON?

We can create, read, update and delete files in python.

How to open file in python?

File Opening in Python-

open() method is used to open the file in the python. It has 2 Parameters –

filename and mode.

There are four different methods (modes) for opening a file:

“r” – Read – Default value. It opens a file for reading and give error if the file does not exist.

“a” – Append – It opens a file for appending the data and creates the file in case if it does not exist.

“w” – Write – It opens a file for writing data and creates the file incase if it does not exist.

“x” – Create – It creates the specified file and returns an error in case if the file exists.

In addition we can also specify if the file should be handled as binary or text mode

“t” – Text – Default value. Text mode

“b” – Binary – Binary mode

For example, assume that a following file named “filename.txt” is located in the same folder as python

filename.txt

This is a sample content of a file named filename.txt for example purpose.

Code-

f=open("filename.txt","rt")
print(f.read())

r and t are default modes so above code is same as f=open(“filename.txt”)

Note- It will give an error in case if file doesn’t exist. and If the file is located in a different location (for ex. file is present in folder named foldername located in C: drive), we will have to specify the file path, like this: “C:\\foldername\filename.txt”

Output-

This is a sample content of a file named filename.txt for example purpose.
You are reading file filename.txt.
How to Read only parts of the file in Python?

read() method by default returns the whole text, but we can also specify how many characters we want to return:

Below code will return only 3 characters of file-

f=open("filename.txt","rt")
print(f.read(3))

Output-

This is a
How to Read Lines of the file in Python?

readline() method is used to return one line of the file.

Code-

f = open("filename.txt", "r")
print(f.readline())

Output-

This is a sample content of a file named filename.txt for example purpose.
How to read file line by line in Python?

We can loop through lines of file to read the whole file line by line as shown in below code-

f = open("filename.txt", "r")
for x in f:
  print(x)
How to close a file in Python?

We should close the file after use, it can be done by using close() method as shown in below code-

f = open("filename.txt", "r")
print(f.readline())
f.close()
How to write to an existing file in Python?

We can use open() method with following parameters as per requirement to write to an existing file.

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

“w” – Write – will overwrite any existing content

Example to open the file and append the content to it

f = open("filename2.txt", "a")
f.write("This content is appended to file")
f.close()

#open and read the file after the appending:
f = open("filename2.txt", "r")
print(f.read())

Example to open the file and overwrite the content to it

f = open("filename3.txt", "w")
f.write("This content has been overwritten.")
f.close()

#open and read the file after the overwriting:
f = open("filename3.txt", "r")
print(f.read())
How to create a New File in Python?

We can use the open() method, with one of the following parameters to create the file in Python:

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

“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

Create a newfile.txt

f = open("newfile.txt", "x")

A new empty file named newfile.txt is created.

Create a newfile.txt if it doesn’t exist

f = open("newfile.txt", "w")
How to delete a file in python?

We can delete a file in python by importing OS module and executing its os.remove() method as shown in below example-

import os
os.remove("filename.txt")

It is advisable to check the existence of file before deleting it to avoid error incase if file doesn’t exist.

import os
if os.path.exists("filename.txt"):
  os.remove("filename.txt")
else:
  print("The file does not exist")
How to delete folder in python?

We can use os.rmdir() method to delete the folder as shown below-

import os
os.rmdir("foldername")

Posted

in

Tags:

Comments

Leave a Reply