0% found this document useful (0 votes)
3 views10 pages

File Handling in Python Text File

The document contains a series of Python programming tasks focused on file handling, including writing to files, reading from files, counting words and lines, and manipulating text data. Each task is presented with code snippets that demonstrate how to implement the desired functionality. The tasks cover various operations such as appending user input, filtering content, and processing text files in different ways.

Uploaded by

shashikant1687
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)
3 views10 pages

File Handling in Python Text File

The document contains a series of Python programming tasks focused on file handling, including writing to files, reading from files, counting words and lines, and manipulating text data. Each task is presented with code snippets that demonstrate how to implement the desired functionality. The tasks cover various operations such as appending user input, filtering content, and processing text files in different ways.

Uploaded by

shashikant1687
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/ 10

1.

Write a Python program to open a text file and write the content of a list of
strings into the file, with each string on a new line.
# List of strings to write into the file
lines = ["Hello, World!", "Python is great.", "File handling in Python"]

# Open the file in write mode


with open('output.txt', 'w') as file:
for line in lines:
# Write each line to the file with a newline character
file.write(line + '\n')

print("File written successfully.")

2. Write a Python program to read the content of a text file and display it line by
line.
# Open the file in read mode
with open('output.txt', 'r') as file:
# Reading line by line
for line in file:
# Display each line (strip is used to remove the newline character)
print(line.strip())

print("File read successfully.")

3. Write a Python program to count the number of lines, words, and characters
in a given text file.
# Initialize counters
line_count = 0
word_count = 0
char_count = 0

# Open the file in read mode


with open('output.txt', 'r') as file:
for line in file:
line_count += 1 # Count each line
words = line.split() # Split the line into words
word_count += len(words) # Count words in the line
char_count += len(line) # Count characters in the line

print(f"Lines: {line_count}")
print(f"Words: {word_count}")
print(f"Characters: {char_count}")

4. Write a Python program to copy the contents of one text file to another file.
# Open the source file in read mode

with open('source.txt', 'r') as src_file:


# Open the destination file in write mode
with open('destination.txt', 'w') as dest_file:
# Copy the content
for line in src_file:
dest_file.write(line)

print("File copied successfully.")

5. Write a Python program to append user input to a text file. The user should be
able to add multiple lines until they choose to stop.
# Open the file in append mode
with open('append_file.txt', 'a') as file:
while True:
# Take user input
user_input = input("Enter a line (or 'stop' to finish): ")

# Break if user types 'stop'


if user_input.lower() == 'stop':
break

# Append the input to the file


file.write(user_input + '\n')

print("User input appended successfully.")

6. Write a Python program to read a text file and print only the lines that start
with a specific word or letter.
# The specific word or letter to check
start_word = input("Enter the word or letter to check for: ")

# Open the file in read mode


with open('output.txt', 'r') as file:
for line in file:
# Check if the line starts with the given word or letter
if line.startswith(start_word):
print(line.strip())

print("Lines that start with", start_word, "displayed.")

7. Write a Python program to read a text file and display the longest word in the
file.
# Initialize variables to store the longest word and its length
longest_word = ""
max_length = 0

# Open the file in read mode


with open('output.txt', 'r') as file:
for line in file:
words = line.split() # Split the line into words
for word in words:
if len(word) > max_length: # Check if the word is longer than
the current longest
longest_word = word
max_length = len(word)

print(f"The longest word is: {longest_word}")

8. Write a Python program to find and replace a specific word in a text file. The
program should update the file with the new word.
# Words to find and replace
old_word = input("Enter the word to replace: ")
new_word = input("Enter the new word: ")

# Open the file in read mode


with open('output.txt', 'r') as file:
content = file.read()

# Replace the old word with the new word


content = content.replace(old_word, new_word)

# Write the updated content back to the file


with open('output.txt', 'w') as file:
file.write(content)

print(f"Replaced '{old_word}' with '{new_word}' in the file.")

9. Write a Python program to merge the contents of two text files and write the
merged content into a third file.
# Open the first file in read mode
with open('file1.txt', 'r') as file1:
content1 = file1.read()

# Open the second file in read mode


with open('file2.txt', 'r') as file2:
content2 = file2.read()

# Open the third file in write mode and write the merged content
with open('merged_file.txt', 'w') as merged_file:
merged_file.write(content1 + '\n' + content2)

print("Files merged successfully.")

10. Write a Python program to count the frequency of each word in a text file
and display the result as a dictionary (word: frequency).
# Initialize an empty dictionary to store word frequency
word_freq = {}

# Open the file in read mode


with open('output.txt', 'r') as file:
for line in file:
words = line.split() # Split the line into words
for word in words:
# Increment the count of the word in the dictionary
word_freq[word] = word_freq.get(word, 0) + 1

# Display the word frequencies


print("Word Frequency:", word_freq)

11. Write a Python program to remove all blank lines from a text file.
# Open the input file in read mode
with open('input.txt', 'r') as infile:
lines = infile.readlines()

# Open the output file in write mode


with open('output.txt', 'w') as outfile:
for line in lines:
if line.strip(): # Write non-blank lines to the output file
outfile.write(line)

print("Blank lines removed successfully.")

12. Write a Python program to read a text file and display the content in reverse
order, i.e., from the last line to the first.
# Open the file in read mode
with open('output.txt', 'r') as file:
lines = file.readlines()

# Reverse the lines and display them


for line in reversed(lines):
print(line.strip())

print("File content displayed in reverse order.")

13. Write a Python program to read a text file and write only the unique words
(words that appear once) into a new file.
# Initialize a dictionary to store word frequency
word_freq = {}

# Open the input file in read mode


with open('input.txt', 'r') as infile:
for line in infile:
words = line.split()
for word in words:
word_freq[word] = word_freq.get(word, 0) + 1

# Open the output file in write mode


with open('unique_words.txt', 'w') as outfile:
for word, count in word_freq.items():
if count == 1:
outfile.write(word + '\n')

print("Unique words written to 'unique_words.txt'.")

14. Write a Python program to check whether a specific word exists in a text file
and print the line number(s) where it occurs.
# The word to search for
search_word = input("Enter the word to search for: ")

# Open the file in read mode


with open('output.txt', 'r') as file:
line_number = 1
found = False
for line in file:
if search_word in line:
print(f"'{search_word}' found in line {line_number}:
{line.strip()}")
found = True
line_number += 1

if not found:
print(f"'{search_word}' not found in the file.")

15. Write a Python program to capitalize the first letter of each word in a text file
and write the updated content to a new file.
# Open the input file in read mode
with open('input.txt', 'r') as infile:
content = infile.read()

# Capitalize the first letter of each word


capitalized_content = content.title()

# Open the output file in write mode and save the updated content
with open('capitalized_output.txt', 'w') as outfile:
outfile.write(capitalized_content)

print("Content with capitalized words saved to 'capitalized_output.txt'.")

16. Write a Python program to split a large text file into smaller files, each
containing a specified number of lines.
# Number of lines per split file
lines_per_file = 5

# Open the input file in read mode


with open('large_file.txt', 'r') as infile:
lines = infile.readlines()

# Split and write to smaller files


for i in range(0, len(lines), lines_per_file):
# Create a new file for each chunk
with open(f'split_file_{i//lines_per_file + 1}.txt', 'w') as split_file:
split_file.writelines(lines[i:i + lines_per_file])

print("File split into smaller files successfully.")

17. Write a Python program to read a text file and write all lines that contain a
specific keyword into a separate file.
# The keyword to search for
keyword = input("Enter the keyword to search for: ")

# Open the input file in read mode


with open('input.txt', 'r') as infile:
# Open the output file in write mode
with open('filtered_output.txt', 'w') as outfile:
for line in infile:
if keyword in line:
outfile.write(line)

print(f"Lines containing '{keyword}' have been written to


'filtered_output.txt'.")

18. Write a Python program to read a text file containing student records (one
record per line) and sort them by marks, then write the sorted records into
another file.
# List to store student records (name and marks)
student_records = []

# Open the file in read mode


with open('students.txt', 'r') as file:
for line in file:
name, marks = line.strip().split(",") # Split each record into name
and marks
student_records.append((name, int(marks)))

# Sort the records by marks in descending order


student_records.sort(key=lambda x: x[1], reverse=True)

# Open the output file in write mode


with open('sorted_students.txt', 'w') as sorted_file:
for record in student_records:
sorted_file.write(f"{record[0]}, {record[1]}\n")

print("Student records sorted by marks and written to


'sorted_students.txt'.")

19. Write a Python program to create a log file that stores the current date and
time every time the program is run.
import datetime

# Get the current date and time


current_time = datetime.datetime.now()

# Open the log file in append mode


with open('log.txt', 'a') as log_file:
log_file.write(f"Program run at: {current_time}\n")

print("Log updated with the current date and time.")

20. Write a Python program to read a large text file in chunks (using a buffer
size) and process each chunk separately (e.g., count words or lines in each
chunk).
# Buffer size (number of bytes to read at a time)
buffer_size = 1024

# Initialize counters
total_lines = 0
total_words = 0

# Open the file in read mode


with open('large_file.txt', 'r') as file:
while True:
# Read a chunk of data
chunk = file.read(buffer_size)
if not chunk:
break

# Count lines and words in the chunk


total_lines += chunk.count('\n')
total_words += len(chunk.split())

print(f"Total Lines: {total_lines}")


print(f"Total Words: {total_words}")

21. Write a Python program to reverse the content of each line in a text file and
save the reversed lines to a new file.
# Open the input file in read mode
with open('input.txt', 'r') as infile:
# Open the output file in write mode
with open('reversed_lines.txt', 'w') as outfile:
for line in infile:
# Reverse the content of each line and write to the output file
reversed_line = line.strip()[::-1]
outfile.write(reversed_line + '\n')

print("Lines reversed and saved to 'reversed_lines.txt'.")

22. Write a Python program to read a text file and count the number of
occurrences of each character (excluding spaces) and display the result.
from collections import Counter

# Initialize a Counter to count characters


char_count = Counter()

# Open the file in read mode


with open('input.txt', 'r') as file:
for line in file:
# Update the Counter with characters from the line, excluding spaces
char_count.update(line.replace(' ', ''))

print("Character frequencies:", dict(char_count))

23. Write a Python program to find and delete lines containing a specific word
from a text file.
# The word to search for
search_word = input("Enter the word to delete lines containing it: ")

# Read the file content and filter out lines containing the word
with open('input.txt', 'r') as infile:
lines = [line for line in infile if search_word not in line]

# Write the filtered lines back to the file


with open('output.txt', 'w') as outfile:
outfile.writelines(lines)

print(f"Lines containing '{search_word}' deleted from the file.")

24. Write a Python program to count the number of lines that contain a specific
word in a text file.
# The word to search for
search_word = input("Enter the word to search for: ")

# Initialize the counter


line_count = 0

# Open the file in read mode


with open('input.txt', 'r') as file:
for line in file:
if search_word in line:
line_count += 1

print(f"Number of lines containing '{search_word}': {line_count}")

25. Write a Python program to read a text file and save a copy of the file with all
characters converted to uppercase.
# Open the input file in read mode
with open('input.txt', 'r') as infile:
content = infile.read()
# Convert the content to uppercase
uppercase_content = content.upper()

# Open the output file in write mode and save the uppercase content
with open('uppercase_output.txt', 'w') as outfile:
outfile.write(uppercase_content)

print("Content converted to uppercase and saved to 'uppercase_output.txt'.")

26. Write a Python program to search for a specific line in a text file and print its
position (line number).
# The line to search for
search_line = input("Enter the line to search for: ")

# Open the file in read mode


with open('input.txt', 'r') as file:
line_number = 1
found = False
for line in file:
if search_line in line:
print(f"'{search_line}' found at line number {line_number}")
found = True
line_number += 1

if not found:
print(f"'{search_line}' not found in the file.")

27. Write a Python program to write numbers from 1 to 100 into a text file, each
number on a new line.
# Open the file in write mode
with open('numbers.txt', 'w') as file:
for number in range(1, 101):
file.write(f"{number}\n")

print("Numbers from 1 to 100 written to 'numbers.txt'.")

28. Write a Python program to create a text file that contains the first 100 prime
numbers, each on a new line.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

# Find the first 100 prime numbers


primes = []
num = 2
while len(primes) < 100:
if is_prime(num):
primes.append(num)
num += 1

# Write the primes to a file


with open('primes.txt', 'w') as file:
for prime in primes:
file.write(f"{prime}\n")

print("First 100 prime numbers written to 'primes.txt'.")

29. Write a Python program to read a text file and write the lines in reverse
order to another file.
# Open the input file in read mode
with open('input.txt', 'r') as infile:
lines = infile.readlines()

# Open the output file in write mode and write lines in reverse order
with open('reversed_lines.txt', 'w') as outfile:
for line in reversed(lines):
outfile.write(line)

print("Lines written in reverse order to 'reversed_lines.txt'.")

30. Write a Python program to count the number of sentences in a text file.
Assume sentences end with periods, exclamation marks, or question marks.
import re

# Open the file in read mode


with open('input.txt', 'r') as file:
content = file.read()

# Use regex to find all sentences (end with '.', '!', or '?')
sentences = re.split(r'[.!?]', content)
# Filter out empty strings from split results
sentences = [sentence for sentence in sentences if sentence.strip()]

print(f"Number of sentences: {len(sentences)}")

You might also like