Python Lab Assignment 5
Topic: File Reading and Writing
1. Read and Print Each Line of a File
with open('[Link]', 'r') as file:
line = [Link]()
while line:
print([Link]())
line = [Link]()
2. Append a Line to an Existing File
with open('[Link]', 'a') as file:
[Link]('This is a new line.\n')
3. Read First 10 Characters, Use seek(5), and Read Next 5 Characters
with open('[Link]', 'r') as file:
print('First 10 characters:', [Link](10))
[Link](5)
print('Next 5 characters from position 6:', [Link](5))
4. Count Words, Lines, and Characters in a File
with open('[Link]', 'r') as file:
content = [Link]()
num_lines = len([Link]('\n'))
num_words = len([Link]())
num_chars = len(content)
print('Lines:', num_lines)
print('Words:', num_words)
print('Characters:', num_chars)
5. Append User Input to a File Until 'STOP' is Entered
with open('[Link]', 'a') as file:
while True:
user_input = input('Enter text (type STOP to end): ')
if user_input == 'STOP':
break
[Link](user_input + '\n')
6. Write a List of Dictionaries to a CSV File
import csv
students = [
{'Name': 'Alice', 'Age': 20, 'Grade': 'A'},
{'Name': 'Bob', 'Age': 22, 'Grade': 'B'},
{'Name': 'Charlie', 'Age': 21, 'Grade': 'A+'}
with open('[Link]', 'w', newline='') as file:
fieldnames = ['Name', 'Age', 'Grade']
writer = [Link](file, fieldnames=fieldnames)
[Link]()
[Link](students)
7. Compare Two Files Line by Line and Report Differences
with open('[Link]', 'r') as file1, open('[Link]', 'r') as file2:
for i, (line1, line2) in enumerate(zip(file1, file2), start=1):
if line1 != line2:
print(f'Difference at line {i}:')
print(f'File1: {[Link]()}')
print(f'File2: {[Link]()}')
8. Write File Lines in Reverse Order to a New File
with open('[Link]', 'r') as file:
lines = [Link]()
with open('reversed_example.txt', 'w') as new_file:
for line in reversed(lines):
new_file.write(line)
9. Replace All Occurrences of a Word in a File
word_to_replace = 'oldword'
replacement_word = 'newword'
with open('[Link]', 'r') as file:
content = [Link]()
content = [Link](word_to_replace, replacement_word)
with open('[Link]', 'w') as file:
[Link](content)
10. Count Occurrences of a Specific Word in a File
word_to_count = 'example'
with open('[Link]', 'r') as file:
content = [Link]()
count = [Link](word_to_count)
print(f'The word "{word_to_count}" appears {count} times in the file.')