Programs on Text File
Program 1 : To print the entire file in bytes
Code :
f=open("TextFile.txt","r")
s=f.read()
a=len(s)
print("The size of the file is ",a,"bytes.")
Output :
The size of the file is 125 bytes.
Program 2 : To print number of lines in entire file.
Code :
f=open("TextFile.txt","r")
s=f.readlines() #Note that we have used readlines() instead of read(). Read "Working with text files" if you don't know the difference. Search it on the above search bar on the page itself.
a=len(s)
print("The number of lines in file is : ",a)
Output :
The number of lines in file is : 1
Program 3 : Write a program to read a text file line by line and display each word separated by '#'.
Code :
f=open("TextFile.txt","r")
l=f.readlines()
s=''
for i in range(len(l)):
a=l[i].split()
for j in a:
s=s+j
s=s+'#'
print(s)
Explanation :
Here's a step-by-step explanation of the code:
f=open("TextFile.txt","r")
: This line opens the file "TextFile.txt" in read mode. The file pointer is now at the beginning of the file.l=f.readlines()
: This line reads all the lines in the file and stores them in a list calledl
. Each element in the list is a string representing a line in the file.s=''
: This line initializes an empty strings
. This string will be used to store all the words from the file, separated by '#' symbols.for i in range(len(l))
: This line starts a loop that iterates over each line in the file. Therange(len(l))
function generates a sequence of numbers from 0 to the length ofl
(exclusive).a=l[i].split()
: This line splits the current linel[i]
into a list of words using thesplit()
method. Thesplit()
method splits a string into a list where each word is a separate element. In this case, it splits the line into words based on spaces.for j in a:
: This line starts a nested loop that iterates over each word in the current line.s=s+j
: This line appends the current wordj
to the end of the strings
.s=s+'#'
: This line appends a '#' symbol to the end of the strings
. This symbol is used to separate words in the final output.print(s)
: This line prints out the final strings
, which contains all the words from the file, separated by '#' symbols