🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Python File Handling

File Handling in Python

File handling in Python involves operations such as reading from and writing to files. Python provides built-in functions and methods for working with files through the built-in open() function.

Opening a File:

To open a file, you use the open() function. The basic syntax is as follows:

file = open("filename", "mode")
  • filename: The name of the file, including its path.
  • mode: The mode in which the file is opened (e.g., "r" for reading, "w" for writing, "a" for appending, "b" for binary).

Reading from a File:

Reading the Entire Content:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

Reading Line by Line:

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() removes leading and trailing whitespaces

Writing to a File:

Writing a String:

with open("output.txt", "w") as file:
    file.write("Hello, World!\\n")
    file.write("Python is great!")

Writing Multiple Lines:

lines = ["Line 1", "Line 2", "Line 3"]

with open("output.txt", "w") as file:
    file.writelines("\\n".join(lines))

Appending to a File:

with open("output.txt", "a") as file:
    file.write("\\nAppending a new line.")

Binary Mode:

with open("binary_data.bin", "wb") as file:
    data = b'\\x48\\x65\\x6c\\x6c\\x6f'  # Binary data (Hello in ASCII)
    file.write(data)

Closing a File:

While the with statement is often used for file handling in Python because it automatically closes the file when the block is exited, you can also explicitly close a file using the close() method:

file = open("example.txt", "r")
content = file.read()
file.close()

Using try...except for File Handling:

try:
    with open("example.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("File not found.")
except Exception as e:
    print(f"An error occurred: {e}")

This try...except block catches specific exceptions like FileNotFoundError (when the file is not found) and a generic Exception (for other errors).

Remember to handle file operations carefully, especially when dealing with file paths, and ensure that you close files properly to avoid resource leaks. The with statement is a good practice as it automatically takes care of closing the file.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.