Python File Handling


A key component of any application is file handling.

There are various functions in Python to create, read, update, and delete files.

You can also search for these topics, python file open function, modes to open the python files, exceptions availability to open the files in python, encode the file open method in python, python write, open and close the file, list the arguments used in python open the file, example for python file open, find the errors and replace the python open file, working of python file open.

Python open() Method

The open() function is the main function to work with files.

Two parameters of Open() function: filename, and mode.

There are four possible ways to opening a file :

  • "r" - Read - Value default. Opens a reading file if the file doesn't exist error
  • "a" - Append - Opens an append file, creates a file if it's not available.
  • "w" - Write - Open a writing file, creates the file if there is no file.
  • "x" - Create - Create the file, return the error when the file exists.

Moreover, you can indicate whether the binary or text file should be treated.

  • "t" - text - Value of default. Mode Text
  • "b" - binary mode "b" (e.g. images)

Syntax

To open a read file, the name of the file is sufficient :

f = open("demofile.txt")

The code above is the same as :

f = open("demofile.txt", "rt")

You do not need to mention them because "r" for reading and "t" for text are default.

Note : Ensure that the file is available otherwise you'll get an error.

You can also search for these topics, python file handling programs example, handling the python file open methods, list out the concept of python file handling, python error file handling, open the python file handling, file handling using in python for what purpose, file handling with statement using python, Example for file handling in pyhton, syntax for file handling in python.

Python Close File - close() Method

When you finish it, it is a recommended practice that you always close the file.

Example :- Close the file when you are finish with it :

f = open("demofile.txt", "r")

# Write code to read data or write data

f.close()

Note : in some circumstances, changes to a file may not appear until you have closed the file, because of the buffering.

You can also search for these topics, python close files after reading, files on exit in python, python to close the files immediately, close the files after writing using python, delete the files in python to close, how to close the readlines using python, check the python exception to close the files, working of python close files functions, check the finally method in python files to close, example for python file closing.

Python Read File Content - read() Method

The read() function is used to read all contents at once or read first 'N' number of characters from a file.

Suppose that we have the file in the same folder as Python : demofile.txt

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

Use the built-in open() function to open the file.

Example 1 :- Reading all contents at a time from "demofile.txt":

f = open("demofile.txt", "r")

print(f.read())

f.close()

Output :-

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

When the file is located at another location, the path to the file must be set as follows :

You can also search for these topics, python open a file on the server binary encoding, default application to open a file on server using python, example for opening a file on the server using python, check the python exist file opening, find the location to file opening on the server in python, python open and found the file on server.

Read Only Parts of the File

The read() method provides the complete text by default, however you can specify how many characters you would like to return :

Example 2:- Return the first 5 characters of the file :

f = open("demofile.txt", "r")

print(f.read(5))

f.close()

Output :-

Hello

You can also search for these topics, python read only parts of the file body, delete the python read only parts of the file, end of the parts of the files in python read only, python use the keys parts read only python file, check the python file modes with read only parts, overwrite the parts in python file read only, python example for part of read only file.

Python Read File Contents Line By Line - readline() Method

The readline() method is used to read a single line from a file.

Example 1 :- Read one line of the file :

f = open("demofile.txt", "r")

print(f.readline())

f.close()

Output :-

Hello! Welcome to demofile.txt

You can read the first two lines by executing readline() twice :

Example 2 :- Read two lines of the file:

f = open("demofile.txt", "r")

print(f.readline())
print(f.readline())

f.close()

Output :-

Hello! Welcome to demofile.txt
This file is for testing purposes.

Example 3 :- Read all lines - Loop through the file line by line :

You may read the entire file, line by line, by looping through file lines :

f = open("demofile.txt", "r")

for x in f:
  print(x)

f.close()

Output :-

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

You can also search for these topics, python read lines from file, how to match the python read lines, python read lines by word, containing the python lines to read a file, count the python lines to read, python generator to read lines, check the limit of python read lines.

Python File Write

You can create a new file or refer to an existing file using open() method in python.

The write() method is used to write data to a specified file.

You can specify the write mode (append or overwrite) of a file using file mode attributes.

You can also search for these topics, python file write line, method to write the python file, how to create the write in file python, python does not work file write, example for Python File Write, empty the file write using python, working of format and function to write a file with python, write a new file and options in python, how to write a python permissions.

Create File and Write Data to an Existing File

You must provide a parameter in the open() function to write to an existing file :

  • "a" - Append - is to be added to the file end.
  • "w" - Write - will overwrite any content already present.

Note: Both parameters will create a file (if does not exist) and then write or append data to the file.

Suppose that we have the file called myfile.txt and it has following contents:

Welcome To
Python

Example 1 :- Open the "myfile.txt" file and add or append the file contents :

f = open("e:\\myfile.txt", "a")
f.write("File Handling")
f.close()

#open and read the file after the appending:
f = open("e:\\myfile.txt", "r")
print(f.read())
f.close()

Output :-

Welcome To
Python
File Handling

Example 2 :- Open the "myfile.txt" file and override the contents :

f = open("e:\\myfile.txt", "w")
f.write("I am new!")
f.close()

#open and read the file after the appending:
f = open("e:\\myfile.txt", "r")
print(f.read())
f.close()

Output :-

I am new!

Note : The "w" technique overwrites the file in its entirety.

You can also search for these topics, python write to an existing file new line, existing file and about the pyton write, working of python to write a existing file function, replace the existing file using python write, how to write a python existing file row by row, file value can be write an existing in python, Example for python write to an existing file.

Create a New File

Use the open() method to create a new Python file with one of the parameters below :

  • "x" - Create - Create a file, returns an error when the file is present
  • "a" - Append - creates a file if there is no specific file
  • "w" - write - creates a file if the file is not specified

Example :- Create a file called "myfile2.txt" :

f = open("E:\\myfile2.txt", "x")

Result : a new empty file is created!

If you run the program second time, it will generate the follwing error:

Traceback (most recent call last):
f = open("e:\\myfile2.txt", "x")
FileExistsError: [Errno 17] File exists: 'e:\\myfile2.txt'

The a and w parameters are will not throw any exception.

You can also search for these topics, python create a new file based on condition, how to create new file in python doesn't exist, python to create a new file keyword, methods to create a files in python, requirements to create new python file, Example for creating a new file in python.

Delete a File

You need to import the OS module and use their os.remove() function in order to delete a file:

Example :- Remove the file "e:\\myfile.txt" :

import os
os.remove("e:\\myfile.txt")
You can also search for these topics, how to delete data from file in python, python delete file if exists, python delete all files in directory with extension, python how delete file, python ftplib delete multiple files, Example for Python Delete File.

Check if File exist

You may wish to check whether the file exists before attempting to open or delete it to avoid error :

Example :- Check if file exists, then delete it :

import os
if os.path.exists("e:\\myfile.txt"):
  os.remove("e:\\myfile.txt")
else:
  print("The file does not exist")
You can also search for these topics, python check if file exists and create, how to check if multiple files exist in python, In python which function can be used to check if a file exists, how check if file exists python, check if document exists mongodb python, Example for python to Check if File exist.

Delete Folder

Use the os.rmdir() method to remove a whole folder :

Example :- Remove the folder "myfolder" :

import os
os.rmdir("myfolder")

Note : only empty folders can be deleted.

You can also search for these topics, delete empty folder in python, python remove all files in directory, python delete files in directory, Example for Delete Folder using python.