File Handling in Python
Video Tutorial
Following are files used for demonstration: file1.txt, file2.txt, and file3.txt
File Handling in Python¶
In [ ]:
fp = open("file1.txt")
for line in fp:
#line = line.rstrip()
print (line, end = '')
In [9]:
fp = open("file1.txt")
for line in fp:
line = line.rstrip()
print (line)
HIT Nidasoshi Hukkeri VTU Belagavi Kanrataka
In [10]:
fp = open("file1.txt")
cont = fp.read()
print (cont)
HIT Nidasoshi Hukkeri VTU Belagavi Kanrataka
In [13]:
print (cont[3:10])
Nidaso
In [14]:
fp = open("file1.txt")
count = 0
for line in fp:
count = count + 1
print ("file1.txt contatins", count, "lines")
file1.txt contatins 4 lines
In [15]:
fp = open("file1.txt")
for line in fp:
line = line.rstrip()
if (line.find('a') >= 0 ):
print (line)
HIT Nidasoshi VTU Belagavi Kanrataka
In [16]:
#Read file contents line by line which contain 'HIT' and display
fhand = open('file1.txt')
for line in fhand:
line = line.rstrip()
if line.find('HIT') >= 0:
print(line)
HIT Nidasoshi
In [17]:
#Read file contents line by line which
#starts with 'HIT' and display
fhand = open('file1.txt')
for line in fhand:
if line.startswith("HIT"):
print (line)
HIT Nidasoshi
In [18]:
#Read file contents line by line which
#does not starts with 'HIT' and display
fhand = open('file1.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('HIT'):
print(line)
Hukkeri VTU Belagavi Kanrataka
In [19]:
#Read file contents line by line which ends
#with 'HIT' and display
fhand = open('file1.txt')
for line in fhand:
line = line.rstrip()
if line.endswith('HIT'):
print(line)
In [20]:
#Read file contents line by line which
#does not ends with 'HIT' and display
fhand = open('file1.txt')
for line in fhand:
line = line.rstrip()
if not line.endswith('HIT'):
print(line)
HIT Nidasoshi Hukkeri VTU Belagavi Kanrataka
In [22]:
file = input("Enter the file name: ")
pat =input("Enter the pattern to be searched: ")
fp = open(file)
for line in fp:
line = line.rstrip()
if (line.find(pat) >= 0 ):
print (line)
Enter the file name: filexytz.txt Enter the pattern to be searched: HIT
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-22-182312d089b6> in <module>() 1 file = input("Enter the file name: ") 2 pat =input("Enter the pattern to be searched: ") ----> 3 fp = open(file) 4 for line in fp: 5 line = line.rstrip() FileNotFoundError: [Errno 2] No such file or directory: 'filexytz.txt'
In [1]:
#Read file name form user and
#Read file contents line by line which
#starts with 'HIT' and display,
#use try and except to handle user errors
fname = input('Enter the file name: ')
try:
fhand = open(fname)
for line in fhand:
if line.startswith('HIT'):
print (line)
except:
print('File cannot be opened:', fname)
exit()
Enter the file name: file1.txt HIT Nidasoshi
In [ ]:
fout = open('output1.txt', 'w')
line1 = "VTU Belagavi"
line2 = "Kanrataka"
fout.write(line1)
fout.write("\n")
fout.write(line2)
fout.close()
In [3]:
fout = open('output.txt', 'a')
line1 = "VTU Belagavi"
line2 = "Kanrataka"
fout.write(line1)
fout.write("\n")
fout.write(line2)
fout.close()
In [5]:
fout = open('output1.txt', 'w')
line1 = "VTU Belagavi"
line2 = "Kanrataka"
fout.write(line1)
fout.write("\n")
fout.write(line2)
fout.close()
In [1]:
fname = input('Enter the file name: ')
try:
fhand = open(fname)
for line in fhand:
words = line.split()
for word in words:
print (word)
except:
print('File cannot be opened:', fname)
exit()
Enter the file name: file1.txt HIT Nidasoshi Hukkeri VTU Belagavi Kanrataka
In [4]:
fname = input('Enter the file name: ')
try:
fhand = open(fname)
for line in fhand:
if line.startswith("Virat"):
words = line.split()
print (words[0])
except:
print('File cannot be opened:', fname)
exit()
Enter the file name: file2.txt Virat Virat
In [ ]:
fname = input('Enter the file name: ')
try:
fhand = open(fname)
for line in fhand:
words = line.split()
print (words)
except:
print('File cannot be opened:', fname)
exit()
In [5]:
fname = input('Enter the file name: ')
try:
fhand = open(fname)
count = 0
total = 0
for line in fhand:
if line.startswith("Virat"):
words = line.split()
#print (words[0])
score = float(words[1]) + float(words[2])
count = count + 1
total = total + score
average = total / count
print ("Total Matches:",count)
print ("Total Runs Scored:",total)
print('Average Score:', average)
except:
print('File cannot be opened:', fname)
exit()
Enter the file name: file2.txt Total Matches: 2 Total Runs Scored: 130.0 Average Score: 65.0
In [ ]:
fname = input('Enter the file name: ')
try:
fhand = open(fname)
count = 0
total = 0
for line in fhand:
words = line.split()
if words[0] != 'Virat':
continue
try:
score = float(words[1])
except:
continue
count = count + 1
total = total + score
average = total / count
print ("Total Matches:",count)
print ("Total Runs in first Innings:",total)
print('Average Score in first Innings:', average)
except:
print('File cannot be opened:', fname)
exit()
In [8]:
fname = input('Enter the file name: ')
try:
fhand = open(fname)
count = 0
total = 0
for line in fhand:
line = line.strip()
words = line.split()
if len(words) != 2:
continue
if words[0] != 'X-DSPAM-Confidence:':
continue
conf = float(words[1])
count = count + 1
total = total + conf
average = total / count
print ('Total number of times X-DSPAM-Confidence occurs in', fname, 'is ', count)
print('Total spam confidence:', total)
print('Average spam confidence:', average)
except:
print('File cannot be opened:', fname)
exit()
Enter the file name: file3.txt Total number of times X-DSPAM-Confidence occurs in file3.txt is 27 Total spam confidence: 20.269400000000005 Average spam confidence: 0.7507185185185187
Summary:
This tutorial discusses the concept of File Handling in Python. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.