0% found this document useful (0 votes)
10 views7 pages

Lab Task on Files.ipynb - Colaboratory

Uploaded by

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

Lab Task on Files.ipynb - Colaboratory

Uploaded by

harshitha2005sri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

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 = f.read()
return contents

filename = 'SetH.txt'
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 = f.readlines()
return lines[:n]

filename = 'SetH.txt'
n = 3
lines = read_n_lines(filename, n)
for line in lines:
print(line.strip())

#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:
f.write(text + '\n')

with open(filename, 'r') as f:


lines = f.readlines()

for line in lines:


print(line.strip())

filename = 'SetH.txt'
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 = f.readlines()
return lines[-n:]

filename = 'SetH.txt'
n = 3
last_n_lines = read_last_n_lines(filename, n)
for line in last_n_lines:
print(line.strip())

#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 = [line.strip() for line in f.readlines()]
return lines

filename = 'SetH.txt'
lines = read_file_lines(filename)
for line in lines:
print(line)

https://colab.research.google.com/drive/1SVWsUs5VwAtYdc5C9qyLhv7YktkvG-Y4#scrollTo=rGnpSxPAolsW&printMode=true 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:
lines.append(line.strip())
return lines

filename = 'SetH.txt'
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 = f.readlines()
return lines

filename = 'SetH.txt'
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 = infile.read().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 = 'SetH.txt'
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 = f.readlines()
return len(lines)

filename = 'SetH.txt'
num_lines = count_lines(filename)
print(f'Number of lines in {filename}: {num_lines}')

https://colab.research.google.com/drive/1SVWsUs5VwAtYdc5C9qyLhv7YktkvG-Y4#scrollTo=rGnpSxPAolsW&printMode=true 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 os.path.getsize(filename)

filename = 'SetH.txt'

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:
f.write(f"{item}\n")

my_list = ["apple", "banana", "cherry"]

write_list_to_file('list.txt', my_list)

with open('list.txt', 'r') as f:


for line in f:
print(line.strip())

#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 = 'source.txt'
dest_filename = 'destination.txt'

copy_file_contents(src_filename, dest_filename)

with open(dest_filename, 'r') as f:


for line in f:
print(line.strip())

https://colab.research.google.com/drive/1SVWsUs5VwAtYdc5C9qyLhv7YktkvG-Y4#scrollTo=rGnpSxPAolsW&printMode=true 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"{line1.strip()}-{line2.strip()}")

return combined_lines

filename1 = 'file1.txt'
filename2 = 'file2.txt'

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 = f.readlines()

if lines:
return random.choice(lines).strip()
else:
return None

filename = 'SetH.txt'

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:
file.read()
except ValueError as e:
if "closed file" in str(e):
return True

return False

with open('test.txt', 'w') as f:


pass

if is_file_closed(f):
print('File is closed.')
else:
print('File is not closed.')

https://colab.research.google.com/drive/1SVWsUs5VwAtYdc5C9qyLhv7YktkvG-Y4#scrollTo=rGnpSxPAolsW&printMode=true 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 = f.readlines()

with open(filename, 'w') as f:


for line in lines:
f.write(line.strip())

filename = 'SetH.txt'

remove_newline_characters(filename)

with open(filename, 'r') as f:


for line in f:
print(line.strip())

#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 = f.read()

words = contents.split() + contents.split(',')

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:
characters.append(char)

return characters

filenames = ['file1.txt', 'file2.txt', 'file3.txt']

characters = extracts(filenames)

print(characters)

https://colab.research.google.com/drive/1SVWsUs5VwAtYdc5C9qyLhv7YktkvG-Y4#scrollTo=rGnpSxPAolsW&printMode=true 5/7
2/18/24, 8:10 PM Lab_Task_on_files.ipynb - Colaboratory
#Write a Python program to generate 26 text files named A.txt, B.txt, and so on up to Z.txt.

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):

f.write(chr(i))

if (i + 1) % num_letters_per_line == 0:
f.write('\n')

filename = 'alphabet.txt'
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(line.strip())

#read the first n lines of a file.

def read_n_lines(filename, n):


with open(filename, 'r') as f:
lines = f.readlines()
return lines[:n]

filename = 'SetH.txt'
n = 3
lines = read_n_lines(filename, n)
for line in lines:
print(line.strip())

#append text to a file and display the text.

def append_text_and_display(filename, text):


with open(filename, 'a') as f:
f.write(text + '\n')

with open(filename, 'r') as f:


lines = f.readlines()

for line in lines:


print(line.strip())

filename = 'SetH.txt'
text = 'This is an example of appending text to a file.'
append_text_and_display(filename, text)

https://colab.research.google.com/drive/1SVWsUs5VwAtYdc5C9qyLhv7YktkvG-Y4#scrollTo=rGnpSxPAolsW&printMode=true 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(line.strip()) 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:
f.write(f"{number}\n")

with open('odd_numbers.txt', 'w') as f:


for number in odd_numbers:
f.write(f"{number}\n")

https://colab.research.google.com/drive/1SVWsUs5VwAtYdc5C9qyLhv7YktkvG-Y4#scrollTo=rGnpSxPAolsW&printMode=true 7/7

You might also like