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

Read/Write Files

Reading and Writing Files in Python

Reading from a File:

Reading the Entire Content:

# Using with statement to automatically close the file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

Reading Line by Line:

# Using with statement to automatically close the file
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:

# Using with statement to automatically close the file
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"]

# Using with statement to automatically close the file
with open("output.txt", "w") as file:
    file.writelines("\\n".join(lines))

Appending to a File:

# Using with statement to automatically close the file
with open("output.txt", "a") as file:
    file.write("\\nAppending a new line.")

Binary Mode:

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

Reading and Writing Files Line by Line:

# Reading from one file and writing to another line by line
with open("input.txt", "r") as input_file, open("output.txt", "w") as output_file:
    for line in input_file:
        output_file.write(line)

Always remember to close the file after reading from or writing to it. The with statement is recommended as it automatically closes the file, even if an exception occurs during the operation.

These examples should give you a good starting point for reading and writing files in Python. Adjust the file paths and content based on your specific requirements.

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.