Working with Files in Python

Print the number of lines in the txt file

# READ FILEdf = open("file1.txt")# read fileread = df.read()
# count number of lines in the fileline = 1for word in read:
if word == '\n':
line += 1
print("Number of lines in file is: ", line)

Print the count of each word in the file

text = open("file1.txt", "r")d = dict()
for line in text:
line = line.strip()
line = line.lower()
words = line.split(" ")

for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
for key in list(d.keys()):
print(key, ":", d[key])

Print the line number next to each line in the file

FileName = "file1.txt"f  = open(FileName,"r")
fileContent = f.read()
number_of_lines = 0line_by_line = fileContent.split("\n")
number_of_lines = len(line_by_line)
print("The number of lines in the file are : ")
print(number_of_lines)
newContents = ""lineIndex = 1for line in line_by_line:
newContents = newContents + "Line #" +str(lineIndex) + ": " + line + "\n"
lineIndex=lineIndex+1
fNewFile = open("NumberedFile-" + FileName,"w")fNewFile.write(newContents)print("File has been created successfully")

Currently pursuing B Tech at MPSTME. Technical Blogger, interested in Google Workspace. Hope to remain a life long student. Created a course on Google Classroom

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store