Programming with Python
LAB 11: File Handling
Part A: File
1. Create a file using mode ‘x’
file = open(“[Link]”, “x”)
2. File handling
3. Insert multiple lines into a file
[Link]([“Hello world”, “I’m Python”, “Don’t afraid to use
me\n”])
4. Reads all the lines in file.
print([Link]())
5. Read from a file line by line
file = open('[Link]', 'w')
[Link]("Hi!\nWelcome to the python programming\nLet's continue
exploring")
file = open('[Link]', 'r')
for python in file:
print(python)
[Link]()
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 = [Link]()
print(len(inp))
print(inp[0:20])
8. Read the text file line by line and remove any whitespace using strip()
while(True):
line = [Link]()
if not line:
break
print([Link]())
9. Read UTF-8 text files
with open('[Link]', encoding='utf8') as f:
for line in f:
print([Link]())
Part B: Test yourself!
1. Write a program that opens an output file with the filename “[Link]”, 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 "[Link]" 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 "[Link]" which
is not starting with an alphabet "T".
The file "[Link]" 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 “[Link]”
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 “[Link]”. 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.