Lab 8- File Handling
Lab 8- File Handling
Part A: File
file.close()
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())
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.