Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

File Handling in Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

File Handling in Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

File Handling in Python

1. Create a Text File and Write into it

file = open('example.txt', 'w') # Open file in write mode


file.write("Hello World!") # Write data
file.close() # Close file

Explanation:

open('example.txt', 'w') : Opens a file named example.txt in write mode.


file.write("Hello World!") : Writes the string into the file.
file.close() : Closes the file to save changes.

2. Difference between w+ and r+ Modes

Key Differences:

w+ mode:
Opens a file for reading and writing.
Deletes existing content if the file exists or creates a new file if it doesn't.
r+ mode:
Opens a file for reading and writing.
Requires the file to already exist; does not delete existing content.

Example:

# w+ mode
with open('wplus_example.txt', 'w+') as file:
file.write("Using w+ mode!")
file.seek(0)
print(file.read()) # Output: Using w+ mode!

# r+ mode
with open('rplus_example.txt', 'r+') as file:
file.write("Using r+ mode!")
file.seek(0)
print(file.read()) # Output: Using r+ mode!

3. Read the First 10 Characters of a Text File

with open('example.txt', 'r') as file:


print(file.read(10)) # Reads the first 10 characters

Explanation:

file.read(10) : Reads the first 10 characters of the file.

4. Using with for Proper Resource Management

with open('example.txt', 'r') as file:


content = file.read() # Automatically closes the file after this
print(content)

Explanation:

The with statement ensures the file is automatically closed after operations,
even if an error occurs.

5. Read and Print Lines with Line Numbers

with open('example.txt', 'r') as file:


for i, line in enumerate(file, start=1):
print(f"Line {i}: {line.strip()}")

Explanation:

enumerate(file, start=1) : Iterates through lines and provides a counter


starting from 1.
line.strip() : Removes leading and trailing whitespace.
6. Use seek() to Move the File Pointer to the Middle

with open('example.txt', 'r') as file:


file_length = len(file.read())
midpoint = file_length // 2
file.seek(midpoint) # Move to the middle
print(file.read()) # Read from the middle to the end

Explanation:

file.seek(midpoint) : Moves the file pointer to the middle.


file.read() : Reads from the current pointer position.

7. Count Lines, Words, and Characters in a File

def file_statistics(file_name):
with open(file_name, 'r') as file:
lines = file.readlines()
num_lines = len(lines)
num_words = sum(len(line.split()) for line in lines)
num_chars = sum(len(line) for line in lines)
return num_lines, num_words, num_chars

print(file_statistics('example.txt')) # Example usage

Explanation:

len(lines) : Counts lines.


len(line.split()) : Counts words in each line.
len(line) : Counts characters in each line.

8. Read a File in Chunks

with open('example.txt', 'r') as file:


while chunk := file.read(1024):
print(chunk)

Explanation:

file.read(1024) : Reads data in chunks of 1024 bytes.

9. Search for a Specific Word in a File

def search_word(file_name, word):


with open(file_name, 'r') as file:
for line in file:
if word in line:
print(line.strip())

search_word('example.txt', 'Python')

Explanation:

Checks each line to see if the word is present using if word in line .

10. Remove Blank Lines from a File

def remove_blank_lines(file_name):
with open(file_name, 'r') as file:
lines = file.readlines()

with open(file_name, 'w') as file:


for line in lines:
if line.strip():
file.write(line)

remove_blank_lines('example.txt')

Explanation:

Writes only non-blank lines back to the file.


line.strip() : Removes leading and trailing whitespace, allowing identification
of blank lines.
11. Count Word Frequency in a File

def word_frequency(file_name):
with open(file_name, 'r') as file:
content = file.read().split()
return {word: content.count(word) for word in set(content)}

print(word_frequency('example.txt'))

12. Reverse the Content of a File

def reverse_file_content(file_name):
with open(file_name, 'r') as file:
content = file.read()
with open(file_name, 'w') as file:
file.write(content[ :-1])

reverse_file_content('example.txt')

Explanation:

content[::-1] : Reverses the entire file content.


Writes the reversed content back into the file.

13. Find and Replace Words in a File

def find_and_replace(file_name, old_word, new_word):


with open(file_name, 'r') as file:
content = file.read()
with open(file_name, 'w') as file:
file.write(content.replace(old_word, new_word))

find_and_replace('example.txt', 'old', 'new')

Explanation:
content.replace(old_word, new_word) : Replaces all occurrences of the old
word with the new word.

14. Merge Two Files into a Third

def merge_files(file1, file2, output_file):


with open(file1, 'r') as f1, open(file2, 'r') as f2, open(output_f
out.write(f1.read())
out.write(f2.read())

merge_files('file1.txt', 'file2.txt', 'merged.txt')

Explanation:

Opens three files simultaneously and writes content from the first two files into
the third.

15. Read and Display File Size

import os

def file_size(file_name):
return os.path.getsize(file_name)

print(f"File size: {file_size('example.txt')} bytes")

Explanation:

os.path.getsize(file_name) : Returns the file size in bytes.

16. Read the Last N Lines of a File

def read_last_n_lines(file_name, n):


with open(file_name, 'r') as file:
lines = file.readlines()
return lines[-n:] # Get the last N lines
print(read_last_n_lines('example.txt', 3))

Explanation:

file.readlines() : Reads all lines into a list.


lines[-n:] : Returns the last n lines of the file.

17. Count Vowels and Consonants in a File

def count_vowels_consonants(file_name):
vowels = 'aeiouAEIOU'
with open(file_name, 'r') as file:
content = file.read()
num_vowels = sum(1 for char in content if char in vowels)
num_consonants = sum(1 for char in content if char.isalpha() a
return num_vowels, num_consonants

print(count_vowels_consonants('example.txt'))

Explanation:

char.isalpha() : Ensures only alphabetic characters are considered.


char in vowels : Checks if a character is a vowel.

18. Backup a File by Copying its Content

def backup_file(source_file, backup_file):


with open(source_file, 'r') as src, open(backup_file, 'w') as bkp:
bkp.write(src.read())

backup_file('example.txt', 'example_backup.txt')

Explanation:

Copies content from the source file into a backup file.


19. Find the Position of the First Occurrence of a Word

def find_word_position(file_name, word):


with open(file_name, 'r') as file:
content = file.read()
position = content.find(word)
return position if position != -1 else "Word not found"

print(find_word_position('example.txt', 'Python'))

Explanation:

content.find(word) : Finds the index of the first occurrence of the word or


returns -1.

20. Split a Large File into Smaller Chunks

def split_file(file_name, chunk_size):


with open(file_name, 'r') as file:
chunk_number = 1
while chunk := file.read(chunk_size):
with open(f'chunk_{chunk_number}.txt', 'w') as chunk_file:
chunk_file.write(chunk)
chunk_number += 1

split_file('large_file.txt', 1024)

Explanation:

Reads and writes the file content in chunks, each of a specified size, creating
multiple smaller files.

21. Default Mode for Opening a File

The default mode is 'r' (read mode).


In this mode:
The file is opened for reading.
If the file does not exist, Python raises a FileNotFoundError .
22. Checking if a File is Opened Successfully

try:
file = open('example.txt', 'r')
print("File opened successfully!")
except FileNotFoundError:
print("File not found!")

Explanation:

A try-except block is used to handle file opening errors gracefully.

23. What Does close() Do?

The close() method closes the file and releases associated system resources.
Ensures that buffered data is written to the file.

Example:

file = open('example.txt', 'r')


file.close()

24. Open a File in Write Mode

file = open('example.txt', 'w')

25. Append Data Without Overwriting

Use the 'a' mode to append data to the end of a file without overwriting existing
content.
26. Reading a Non-Existent File

If you attempt to read a file that does not exist, Python raises a
FileNotFoundError .

27. Method to Read Entire File as a String

Use the read() method.

Example:

with open('example.txt', 'r') as file:


content = file.read()
print(content)

28. Difference Between a and a+ Modes

a mode:
Opens a file for appending.
Writing starts at the end of the file; reading is not allowed.
a+ mode:
Allows both reading and appending to the file.

Example:

with open('example.txt', 'a+') as file:


file.write("Appending data.")
file.seek(0) # Move to the start of the file
print(file.read())

29. Syntax of the open() Function

open(file, mode='r', buffering=-1, encoding=None, errors=None)


file : Name or path of the file.
mode : File operation mode ( 'r' , 'w' , 'a' , etc.).
buffering : Controls buffering; -1 (default) enables automatic buffering.
encoding : Specifies file encoding.
errors : Controls how encoding errors are handled.

30. Methods for Reading Data

read() : Reads the entire file content as a string.


readline() : Reads the next line from the file.
readlines() : Reads all lines and returns them as a list.

You might also like