Practical Questions

M3-R5.1 · Chapter 7: File Processing · 2 min read

.  Practical Programs

6.1  Write and Read a File

# Step 1: Write data to a file

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

    f.write('Name: Rahul\n')

    f.write('Roll: 101\n')

    f.write('Marks: 85\n')

 

# Step 2: Read the file back

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

    print(f.read())

 

# Output:

# Name: Rahul

# Roll: 101

# Marks: 85

6.2  Count Words and Lines in a File

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

    content = f.read()

 

lines = content.split('\n')

words = content.split()

 

print(f'Total Lines: {len(lines)}')

print(f'Total Words: {len(words)}')

print(f'Total Characters: {len(content)}')

6.3  Copy Content from One File to Another

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

    data = src.read()

 

with open('destination.txt', 'w') as dst:

    dst.write(data)

 

print('File copied successfully!')

6.4  Append Log Entries to a File

import datetime

 

def write_log(message):

    with open('app.log', 'a') as f:

        timestamp = datetime.datetime.now()

        f.write(f'[{timestamp}] {message}\n')

 

write_log('Application started')

write_log('User logged in')

write_log('Error: File not found')

 

# app.log will have all three entries appended

6.5  Search for a Word in a File

search_word = 'Python'

count = 0

 

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

    for line_no, line in enumerate(f, start=1):

        if search_word in line:

            count += 1

            print(f'Found at line {line_no}: {line.strip()}')

 

print(f'\n"{search_word}" found {count} time(s)')