0% found this document useful (0 votes)
16 views3 pages

Python File Handling Techniques

The document contains 5 questions and their solutions about file handling in Python. It introduces functions to read a file and store it in a list, find the longest words in a file, combine corresponding lines from two files, and check if a file is open or closed. Sample programs and outputs are provided for each question.

Uploaded by

Harshit Bansal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views3 pages

Python File Handling Techniques

The document contains 5 questions and their solutions about file handling in Python. It introduces functions to read a file and store it in a list, find the longest words in a file, combine corresponding lines from two files, and check if a file is open or closed. Sample programs and outputs are provided for each question.

Uploaded by

Harshit Bansal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Practical – 7

File Handling
Submitted By: Harshit Bansal (18BCS3805)
Q1: Write a Python program to read a file line by line and store it
into a list.
Program
def file_read(fname):
with open(fname) as f:
content_list = [Link]()
print(content_list)

file_read('[Link]')

Output

Q2: Write a python program to find the longest words.


Program
def longest_word(filename):
with open(filename, 'r') as infile:
words = [Link]().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]

print(longest_word('[Link]'))

Output
Q3: Write a python program to find the longest words.
Program
def longest_word(filename):
with open(filename, 'r') as infile:
words = [Link]().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]

print(longest_word('[Link]'))

Output

Q4: Write a Python program to combine each line from first file
with the corresponding line in second file.
Program
with open('[Link]') as fh1, open('[Link]') as fh2:
for line1, line2 in zip(fh1, fh2):
# line1 from [Link], line2 from [Link]
print(line1+line2)

Output
Q5: Write a Python program to assess if a file is closed or not.
Program
f = open('[Link]','r')
print([Link])
[Link]()
print([Link])

Output

You might also like