Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

125004102

jayasakthi

EXERCISE:7- FileI/O

with open('input.txt', 'w') as file:


while True:
line = input("Enter a line of text (or 'End' to finish): ")

if line.strip() == 'End':
break

file.write(line + '\n')

print("Input saved to 'input.txt'")

file_name = input("Enter the name of the text file: ")

try:
with open(file_name, 'r') as file:
print("Reading all contents of the file at once using read():")
file_contents = file.read()
print(file_contents)

file.seek(0)
print("\nReading the contents of the file line by line using readline():")
while True:
line = file.readline()
if not line:
break
print(line, end='')

except FileNotFoundError:
print(f"File '{file_name}' not found.")

import csv

book_data = [
{
'acc_no': '001',
'title': 'The Great Gatsby',
'author': 'F. Scott Fitzgerald',
'publisher': 'Scribner',
'year': '1925',
'edition': '1st',
'price': '$10.99'
},
{
'acc_no': '002',
'title': 'To Kill a Mockingbird',
'author': 'Harper Lee',
'publisher': 'J. B. Lippincott & Co.',
'year': '1960',
'edition': '1st',
'price': '$12.99'
}
]

csv_file = 'books.csv'

try:
with open(csv_file, 'w', newline='') as file:
fieldnames = ['acc_no', 'title', 'author', 'publisher', 'year', 'edition', 'price']
writer = csv.DictWriter(file, fieldnames=fieldnames)

writer.writeheader()

writer.writerows(book_data)

print(f'Data with header row written to {csv_file}')

with open(csv_file, 'a', newline='') as file:


writer = csv.DictWriter(file, fieldnames=fieldnames)

writer.writerows(book_data)

print(f'Data without header row appended to {csv_file}')

except Exception as e:
print(f"An error occurred: {str(e)}")

import csv

student_data = [
{
'Reg_no': '101',
'name': 'Alice',
'Math': 90,
'Science': 85,
'English': 88,
},
{
'Reg_no': '102',
'name': 'Bob',
'Math': 78,
'Science': 92,
'English': 86,
},
{
'Reg_no': '103',
'name': 'Charlie',
'Math': 85,
'Science': 90,
'English': 75,
},
]

csv_file = 'student_marks.csv'

with open(csv_file, 'w', newline='') as file:


fieldnames = ['Reg_no', 'name', 'Math', 'Science', 'English']
writer = csv.DictWriter(file, fieldnames=fieldnames)

writer.writeheader()

writer.writerows(student_data)

print(f'Data with header row written to {csv_file}')

with open(csv_file, 'r') as file:


reader = csv.DictReader(file)
data = list(reader)

for student in data:


student['Average'] = sum(int(student[subject]) for subject in ['Math', 'Science', 'English']) / 3

subject_averages = {}
for subject in ['Math', 'Science', 'English']:
subject_averages[subject] = sum(int(student[subject]) for student in data) / len(data)

for student in data:


student.update(subject_averages)

with open(csv_file, 'w', newline='') as file:


fieldnames = ['Reg_no', 'name', 'Math', 'Science', 'English', 'Average']
writer = csv.DictWriter(file, fieldnames=fieldnames)

writer.writeheader()
writer.writerows(data)

print(f'Averages calculated and added to {csv_file}')

You might also like