Programming with Python
LAB 11: File Handling
Part A: File
1. Create a file using mode ‘x’
file = open(“test.txt”, “x”)
2. File handling
3. Insert multiple lines into a file
file.writelines([“Hello world”, “I’m Python”, “Don’t afraid to use
me\n”])
4. Reads all the lines in file.
print(file.readline())
5. Read from a file line by line
file = open('practice.txt', 'w')
file.writelines("Hi!\nWelcome to the python programming\nLet's continue
exploring")
file = open('practice.txt', 'r')
for python in file:
print(python)
file.close()
6. Count the lines in text file
count = 0
for line in file:
count = count + 1
print('Line Count:', count)
Programming with Python
7. Read length of the text in a file and display string using slice.
inp = file.read()
print(len(inp))
print(inp[0:20])
8. Read the text file line by line and remove any whitespace using strip()
while(True):
line = file.readline()
if not line:
break
print(line.strip())
9. Read UTF-8 text files
with open('practice.txt', encoding='utf8') as f:
for line in f:
print(line.strip())
Part B: Test yourself!
1. Write a program that opens an output file with the filename “my.txt”, writes the name of
animal, some fruit, and your country to the file on separate lines, then close the file.
2. Write a function in python to read the content from a text file "python.txt" line by line and
display the same on screen.
Create a text file and store the lines as below:
3. Write a function in python to count the number of lines from a text file "story.txt" which
is not starting with an alphabet "T".
The file "story.txt" should contains any story of yours or you may use the following lines:
Once upon a time, a farmer had a goose that laid a golden egg every day. The egg provided
enough money for the farmer and his wife for their day-to-day needs. The farmer and his
wife were happy for a long time. But one day, the farmer got an idea and thought, “Why
should I take just one egg a day? Why can’t I take all of them at once and make a lot of
money?”
4. Write a Python program to remove duplicate lines from a text file. Your program should:
a. Write a content below into a text file named “Revision.txt”
Hello this is Python
Good Morning
Hello this is Python
Programming with Python
I love Python
coding is the best!
b. Create an empty text file named “newRevision.txt”. You will write the new
content after removing the duplicate lines into this file.
c. Create an empty list to store the unique lines of the file.