2/18/24, 8:10 PM Lab_Task_on_files.
ipynb - Colaboratory
#1. Write a Python program to read an entire text file.
def read_entire_file(filename):
with open(filename, 'r') as f:
contents = [Link]()
return contents
filename = '[Link]'
contents = read_entire_file(filename)
print(contents)
#Write a Python program to read first n lines of a file.
def read_n_lines(filename, n):
with open(filename, 'r') as f:
lines = [Link]()
return lines[:n]
filename = '[Link]'
n = 3
lines = read_n_lines(filename, n)
for line in lines:
print([Link]())
#Write a Python program to append text to a file and display the text.
def append_text_and_display(filename, text):
with open(filename, 'a') as f:
[Link](text + '\n')
with open(filename, 'r') as f:
lines = [Link]()
for line in lines:
print([Link]())
filename = '[Link]'
text = 'This is an example of appending text to a file.'
append_text_and_display(filename, text)
#Write a Python program to read last n lines of a file.
def read_last_n_lines(filename, n):
with open(filename, 'r') as f:
lines = [Link]()
return lines[-n:]
filename = '[Link]'
n = 3
last_n_lines = read_last_n_lines(filename, n)
for line in last_n_lines:
print([Link]())
#Write a Python program to read a file line by line and store it into a list.
def read_file_lines(filename):
with open(filename, 'r') as f:
lines = [[Link]() for line in [Link]()]
return lines
filename = '[Link]'
lines = read_file_lines(filename)
for line in lines:
print(line)
[Link] 1/7
2/18/24, 8:10 PM Lab_Task_on_files.ipynb - Colaboratory
#Write a Python program to read a file line by line store it into a variable.
def read_file_line_by_line(filename):
with open(filename, 'r') as f:
lines = []
for line in f:
[Link]([Link]())
return lines
filename = '[Link]'
contents = read_file_line_by_line(filename)
for line in contents:
print(line)
#Write a Python program to read a file line by line store it into an array.
def read_file_line_by_line(filename):
with open(filename, 'r') as f:
lines = [Link]()
return lines
filename = '[Link]'
lines = read_file_line_by_line(filename)
file_contents = ''.join(lines)
print(file_contents)
#Write a python program to find the longest words in a file
def longest_word(filename):
with open(filename, 'r') as infile:
words = [Link]().split()
max_len = 0
longest_words = []
for word in words:
if len(word) > max_len:
max_len = len(word)
for word in words:
if len(word) == max_len:
longest_words.append(word)
return longest_words
filename = '[Link]'
longest_words = longest_word(filename)
print(f"Longest words in {filename}: {longest_words}")
#Write a Python program to count the number of lines in a text file.
def count_lines(filename):
with open(filename, 'r') as f:
lines = [Link]()
return len(lines)
filename = '[Link]'
num_lines = count_lines(filename)
print(f'Number of lines in {filename}: {num_lines}')
[Link] 2/7
2/18/24, 8:10 PM Lab_Task_on_files.ipynb - Colaboratory
#Write a Python program to get the file size of a plain file.
import os
def get_file_size(filename):
return [Link](filename)
filename = '[Link]'
file_size = get_file_size(filename)
print(f'File size of {filename}: {file_size} bytes')
#Write a Python program to write a list to a file.
def write_list_to_file(filename, list_data):
with open(filename, 'w') as f:
for item in list_data:
[Link](f"{item}\n")
my_list = ["apple", "banana", "cherry"]
write_list_to_file('[Link]', my_list)
with open('[Link]', 'r') as f:
for line in f:
print([Link]())
#Write a Python program to copy the contents of a file to another file .
def copy_file_contents(src_filename, dest_filename):
with open(src_filename, 'r') as src_file:
with open(dest_filename, 'w') as dest_file:
for line in src_file:
dest_file.write(line)
src_filename = '[Link]'
dest_filename = '[Link]'
copy_file_contents(src_filename, dest_filename)
with open(dest_filename, 'r') as f:
for line in f:
print([Link]())
[Link] 3/7
2/18/24, 8:10 PM Lab_Task_on_files.ipynb - Colaboratory
#Write a Python program to combine each line from first file with the corresponding line in second file.
def combine_lines(filename1, filename2):
combined_lines = []
with open(filename1, 'r') as file1, open(filename2, 'r') as file2:
for line1, line2 in zip(file1, file2):
combined_lines.append(f"{[Link]()}-{[Link]()}")
return combined_lines
filename1 = '[Link]'
filename2 = '[Link]'
combined_lines = combine_lines(filename1, filename2)
for line in combined_lines:
print(line)
#Write a Python program to read a random line from a file.
import random
def read_random_line(filename):
with open(filename, 'r') as f:
lines = [Link]()
if lines:
return [Link](lines).strip()
else:
return None
filename = '[Link]'
random_line = read_random_line(filename)
if random_line:
print(f'Random line: "{random_line}"')
else:
print('File is empty.')
#Write a Python program to assess if a file is closed or not.
def is_file_closed(file):
try:
[Link]()
except ValueError as e:
if "closed file" in str(e):
return True
return False
with open('[Link]', 'w') as f:
pass
if is_file_closed(f):
print('File is closed.')
else:
print('File is not closed.')
[Link] 4/7
2/18/24, 8:10 PM Lab_Task_on_files.ipynb - Colaboratory
#Write a Python program to remove newline characters from a file.
def remove_newline_characters(filename):
with open(filename, 'r') as f:
lines = [Link]()
with open(filename, 'w') as f:
for line in lines:
[Link]([Link]())
filename = '[Link]'
remove_newline_characters(filename)
with open(filename, 'r') as f:
for line in f:
print([Link]())
#Write a Python program that takes a text file as input and returns the number of words of a given text file. Note: Some words can be se
def count_words(filename):
with open(filename, 'r') as f:
contents = [Link]()
words = [Link]() + [Link](',')
words = [word for word in words if word]
return len(words)
filename = input("Enter the filename: ")
num_words = count_words(filename)
print(f"The number of words in the file '{filename}' is: {num_words}")
#Write a Python program to extract characters from various text files and puts them into a list.
def extracts(filenames):
characters = []
for filename in filenames:
with open(filename, 'r') as f:
for line in f:
for char in line:
[Link](char)
return characters
filenames = ['[Link]', '[Link]', '[Link]']
characters = extracts(filenames)
print(characters)
[Link] 5/7
2/18/24, 8:10 PM Lab_Task_on_files.ipynb - Colaboratory
#Write a Python program to generate 26 text files named [Link], [Link], and so on up to [Link].
import os
filenames = [chr(i) + ".txt" for i in range(65, 91)]
for filename in filenames:
with open(filename, 'w') as f:
pass
print(filenames)
#Write a Python program to create a file where all letters of English alphabet are listed by specified number of letters on each line.
def create_file_with_alphabets(filename, num_letters_per_line):
with open(filename, 'w') as f:
for i in range(65, 91):
[Link](chr(i))
if (i + 1) % num_letters_per_line == 0:
[Link]('\n')
filename = '[Link]'
num_letters_per_line = 5
create_file_with_alphabets(filename, num_letters_per_line)
with open(filename, 'r') as f:
for line in f:
print([Link]())
#read the first n lines of a file.
def read_n_lines(filename, n):
with open(filename, 'r') as f:
lines = [Link]()
return lines[:n]
filename = '[Link]'
n = 3
lines = read_n_lines(filename, n)
for line in lines:
print([Link]())
#append text to a file and display the text.
def append_text_and_display(filename, text):
with open(filename, 'a') as f:
[Link](text + '\n')
with open(filename, 'r') as f:
lines = [Link]()
for line in lines:
print([Link]())
filename = '[Link]'
text = 'This is an example of appending text to a file.'
append_text_and_display(filename, text)
[Link] 6/7
2/18/24, 8:10 PM Lab_Task_on_files.ipynb - Colaboratory
#Read numbers from a file and write even and odd numbers to separate files.
def read_numbers_and_write(filename):
with open(filename, 'r') as f:
numbers = [int([Link]()) for line in f]
even_numbers = []
odd_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
with open('even_numbers.txt', 'w') as f:
for number in even_numbers:
[Link](f"{number}\n")
with open('odd_numbers.txt', 'w') as f:
for number in odd_numbers:
[Link](f"{number}\n")
[Link] 7/7