Python file handling programs
In this post, you will learn different file handling programs using the Python programming language. Python has several in-built methods for file handling. File handling is an important piece of any web application. A file needs to be processed for certain tasks to be done. Python file handling functions allow us to store, access, and manipulate files.
Python Read File
Python provides open() method to open or create a file object. Here is the program to read a text file line by line.
f = open("demo.txt", "r")
fr = f.read()
print(fr)
Python Count File Line & Length
In Python, it is easy to loop through a file and count each of the lines in a file.
fhand = open('demo.txt')
count = 0
for line in fhand:
count = count + 1
print('Line Count:', count)
Output of the above code-
(env) c:\python37\Scripts\projects>filehandling.py
Line Count: 5
Get length of a file
Python provides len() method to count all characters of a file.
f = open("demo.txt", "r")
fr = f.read()
print('Length of file:', len(fr))
Output of the above code-
Length of file: 326
Python file slicing
The following code string slicing first 49 characters of an opened file.
f = open("demo.txt", "r")
fr = f.read()
print(fr[:49])
Output of the above code-
Sugary drinks are among the most fattening items
Python file searching
When we are looking through data in a file, we want to read some portion of a file and ignore most of the lines. This can be easily done in python.
There is a string method startswith() to select only those lines with the desired prefix. The given code reads the file start with 'Fish' -
fhand = open('demo.txt')
for line in fhand:
line = line.rstrip()
if line.startswith('Fish'):
print(line)
Output of the above code-
Fish is a great source of high-quality protein and healthy fat.
Python Choose & Read File Name
In the above programs, we have worked on a static file. In the given example, we have provided user to choose the file to read.
fname = input('Enter the file name: ')
fhand = open(fname)
count = 0
for line in fhand:
count = count + 1
print('Line Count:', count)
Output of the above code-
Enter the file name: demo.txt
Line Count: 5
Python File Exception Handling
Suppose the user has provided something else that is not a file name. The program will definitely raise the file not found error. We can easily handle such type of errors using exception handling.
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
count = 0
for line in fhand:
line = line.rstrip()
if line.startswith('Fish'):
print(line)
Output of the above code-
Fish is a great source of high-quality protein and healthy fat.
Related Articles
CRUD operations in Python using MongoDB connectorWrite Python Pandas Dataframe to CSV
Quick Introduction to Python Pandas
Python Pandas DataFrame
Python3 Tkinter Messagebox
Python get visitor information by IP address
Python Webbrowser
Python Tkinter Overview and Examples
Python Turtle Graphics Overview
Factorial Program in Python
Python snake game code with Pygame
Python JSON Tutorial - Create, Read, Parse JSON file
Python convert xml to dict
Python convert dict to xml