File Operations and Exceptions

1: Reading a large file

with open('1.txt', 'r') as f:
    content = f.readline()
    while len(content) > 0:
        print(content)
        content = f.readline()

2: Reading lines containing the chaarcter 'python' from a large file

with open('1.txt', 'r') as f:
    count = 0
    content = f.readline()
    while len(content) > 0:
        if 'python' in content:
            count += 1
            print(content)
        content = f.readline()
    print(f'python character occurrences: {count}')

3: Creating a backup of a file

old_file = input('Enter the filename in the current directory to back up:')
num = old_file.rfind('.')</br>
new_file = old_file[0:num] + 'backup' + old_file[num:]

old = open(old_file, 'r')
new = open(new_file, 'w')
content = old.readline()
while len(content) > 0:
    new.write(content)
    content = old.readline()

old.close()
new.close()

4: Renaming all files in a specified directory

import os

listdir = os.listdir('../test')
for temp in listdir:
    new_file = 'abc-' + temp
    os.chdir('../test')
    os.rename(temp, new_file)

Tags: file operations exceptions python

Posted on Tue, 21 Jul 2026 16:21:11 +0000 by synergypoint