Python: Read and Write Text Files

Python Tutorial: Reading and Writing Text Files

Python Tutorial: Reading and Writing Text Files

This tutorial will guide you through the process of reading and writing text files in Python. We’ll cover the fundamental concepts and provide practical examples to solidify your understanding. We will focus on clear, concise code, including debugging tips.

Example 1: Writing a Simple Text File

This example demonstrates how to write a single line of text to a file. We’ll use the `open()` function with the ‘w’ (write) mode to create a new file, or overwrite an existing one. It’s crucial to include the `with` statement to ensure the file is properly closed, even if errors occur.


# Define the filename
filename = "my_file.txt"

# Define the text to write
text = "Hello, world!nThis is a new line."

# Open the file in write mode ('w')
try:
    with open(filename, 'w') as file:
        # Write the text to the file
        file.write(text)
    print(f"Successfully wrote to {filename}")

except Exception as e:
    print(f"An error occurred: {e}")

Explanation:

  • `filename = “my_file.txt”`: This line assigns the string “my_file.txt” to the variable `filename`. This variable represents the name of the file we intend to create or modify.
  • `text = “Hello, world!nThis is a new line.”`: This line defines the string that will be written into the file. The `n` character represents a newline, so the text will be written on separate lines.
  • `with open(filename, ‘w’) as file:`: This is the core of the file writing operation.
    • `open(filename, ‘w’)`: This function attempts to open the file specified by `filename` in write mode (‘w’). If the file doesn’t exist, it creates it. If the file does exist, the ‘w’ mode will overwrite its contents.
    • `as file`: This assigns the opened file object to the variable `file`. We’ll use this variable to interact with the file.
    • `with … as`: The `with` statement provides a convenient way to manage resources like files. It automatically closes the file when the block of code inside the `with` statement is finished, even if an error occurs. This is important to avoid data corruption and resource leaks.
  • `file.write(text)`: This is the method that actually writes the string `text` to the file. The `write()` method takes a string argument and writes it to the file. Note that `write()` does not automatically add a newline character. You need to explicitly include `n` in the string if you want a new line.
  • `print(f”Successfully wrote to {filename}”)`: This prints a success message to the console, confirming that the writing operation completed without errors.
  • `except Exception as e:`: This block handles potential exceptions that might occur during the file writing process (e.g., permission errors). It prints an error message to the console, which can be helpful for debugging.

Common Mistakes:

  • Forgetting the `with` statement: Without the `with` statement, you’ll need to manually call `file.close()` which can lead to errors if the program crashes before the file is closed.
  • Incorrect file mode: Using ‘w+’ (write and read) instead of ‘w’ (write only) if you only want to write to the file. ‘w+’ will try to read the file, too.
  • Not handling potential errors: Not including a `try…except` block can cause the program to crash if an error occurs during file operations.

# Define the filename
filename = "my_file.txt"

# Define the text to write
text = "Hello, world!nThis is a new line."

# Open the file in write mode ('w')
try:
    with open(filename, 'w') as file:
        # Write the text to the file
        file.write(text)
    print(f"Successfully wrote to {filename}")

except Exception as e:
    print(f"An error occurred: {e}")

Output:


Successfully wrote to my_file.txt

Example 2: Reading a Text File

This example demonstrates how to read the content of a text file. We use the `open()` function with the ‘r’ (read) mode to open the file and then read its entire content using the `read()` method. The `with` statement is still used for proper file handling.


# Define the filename
filename = "my_file.txt"

# Open the file in read mode ('r')
try:
    with open(filename, 'r') as file:
        # Read the entire content of the file
        content = file.read()

    # Print the content
    print("File content:")
    print(content)

except FileNotFoundError:
    print(f"File not found: {filename}")
except Exception as e:
    print(f"An error occurred: {e}")

Explanation:

  • `filename = “my_file.txt”`: Same as in Example 1.
  • `content = file.read()`: This reads the entire contents of the file into a single string variable called `content`.
  • `print(“File content:”)` and `print(content)`: These lines print the content of the file to the console.
  • `except FileNotFoundError`: This handles the case where the file does not exist.
  • `except Exception as e`: Handles other potential errors.

# Define the filename
filename = "my_file.txt"

# Open the file in read mode ('r')
try:
    with open(filename, 'r') as file:
        # Read the entire content of the file
        content = file.read()

    # Print the content
    print("File content:")
    print(content)

except FileNotFoundError:
    print(f"File not found: {filename}")
except Exception as e:
    print(f"An error occurred: {e}")

Output:


File content:
Hello, world!
This is a new line.

Example 3: Reading a Text File Line by Line

This example demonstrates how to read a text file line by line. This is useful when you want to process each line of the file individually. We use the `readline()` method to read a single line, or the `readlines()` method to read all lines into a list.


# Define the filename
filename = "my_file.txt"

# Open the file in read mode ('r')
try:
    with open(filename, 'r') as file:
        # Read the file line by line using readline()
        #line = file.readline()
        #while line:
        #    print(line.strip()) # Remove leading/trailing whitespace
        #    line = file.readline()

        # Read all lines into a list using readlines()
        lines = file.readlines()

    # Print each line
    print("File content (line by line):")
    for line in lines:
        print(line.strip()) # Remove leading/trailing whitespace

except FileNotFoundError:
    print(f"File not found: {filename}")
except Exception as e:
    print(f"An error occurred: {e}")

Explanation:

  • The code uses `file.readlines()` which reads the entire file and returns a list of strings, where each string represents a line in the file.
  • The code iterates through the `lines` list using a `for` loop.
  • Inside the loop, `line.strip()` is used to remove any leading or trailing whitespace (spaces, tabs, newlines) from each line before printing it. This is a good practice to ensure that the output is clean and formatted correctly.

# Define the filename
filename = "my_file.txt"

# Open the file in read mode ('r')
try:
    with open(filename, 'r') as file:
        # Read the file line by line using readline()
        #line = file.readline()
        #while line:
        #    print(line.strip()) # Remove leading/trailing whitespace
        #    line = file.readline()

        # Read all lines into a list using readlines()
        lines = file.readlines()

    # Print each line
    print("File content (line by line):")
    for line in lines:
        print(line.strip()) # Remove leading/trailing whitespace

except FileNotFoundError:
    print(f"File not found: {filename}")
except Exception as e:
    print(f"An error occurred: {e}")

Output:


File content (line by line):
Hello, world!
This is a new line.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies and similar technologies to enhance your experience on wobizdu.com, analyze site traffic, personalize content, and deliver relevant ads. Some cookies are essential for the site to function, while others help us improve performance and user experience. You may accept all cookies, decline optional ones, or customize your settings. Review our Privacy Policy to learn more.