File Handling in Python: Reading, Writing, and Appending

 

Definition of File Handling: 

File handling refers to the process of creating, opening, reading, writing, appending, and closing files in a program. It allows managing files to store and retrieve data efficiently. File handling is essential for tasks like saving user data, processing logs, and generating reports.


In Python, file handling is performed using built-in functions such as:

  • open(): Opens a file in the specified mode (e.g., read, write, append).
  • read() and readline(): Read data from a file.
  • write(): Write data to a file.
  • close(): Closes the file to free up resources.

File modes include:

  • "r": Read mode (default).
  • "w": Write mode (overwrites existing content).
  • "a": Append mode (adds new content to the end).
  • "r+": Read and write mode.


Reading from a file:

Program:

# Reading from a file
f = open("fruits.txt", "r")  # Opens the file in read mode
content = f.read()  # Reads the entire content of the file
print("Initial content of the file:")
print(content)  # Prints the content
f.close()  # Closes the file


Output:

Assuming fruits.txt initially contains:

banana
grapes

The output will be :

Initial content of the file:
banana
grapes




Writing to a file:

Program:

# Writing to a file (overwrites existing content)
f = open("fruits.txt", "w")  # Opens the file in write mode
f.write("banana\n")  # Writes "banana" followed by a newline
f.write("grapes\n")  # Writes "grapes" followed by a newline
f.close()  # Closes the file


Output:

After this code executes, the file fruits.txt will contain:

banana
grapes


Reading and updating the file:

Program:

# Reading and updating the file
f = open("fruits.txt", "r+")  # Opens the file in read-write mode
print("Content after writing 'banana' and 'grapes':")
print(f.read())  # Reads and prints the updated content
f.close()  # Closes the file


Output:

Content after writing 'banana' and 'grapes':
banana
grapes




Appending to a File:

Program:

# Appending to the file
f = open("fruits.txt", "a")  # Opens the file in append mode
f.write("apple\n")  # Appends "apple" followed by a newline
f.write("orange\n")  # Appends "orange" followed by a newline
f.close()  # Closes the file


Output:

After executing the above code, the content of fruits.txt will be:

banana
grapes
apple
orange

Post a Comment

0 Comments