PYTHON Tutorial

File Handling

Introduction:

File handling allows Python programs to interact with files, reading and writing data. It's vital for storing and manipulating information.

Key Concepts:

  • File Object: Represents an open file for reading or writing.
  • File Modes: Indicate the access mode: 'r' for reading, 'w' for writing, 'a' for appending, 'r+' for reading and writing.
  • Python File Read: Uses the read() method to retrieve the file content as a string.
  • Python File Write: Employs the write() method to write data to the file.

Example:

Reading and Writing to Files in Python

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

# Write data to the file
file.write('Hello World!')

# Close the file after writing
file.close()

# Open the file in read mode
file = open('myfile.txt', 'r')

# Read data from the file
data = file.read()

# Close the file after reading
file.close()

# Print the read data
print(data)

Output:

Hello World!

Conclusion:

File handling in Python is straightforward, allowing you to easily read, write, and modify files. Understanding these concepts and applying them effectively can significantly enhance your programming capabilities.