Python: Read and Write Text Files

Python Text File Tutorial

Python Text File Tutorial: Reading and Writing

This tutorial will guide you through the process of reading and writing text files using Python. We’ll start with simple examples and gradually build upon them.

Understanding Text Files

A text file is a plain file containing text data. These files are commonly used to store information like notes, configuration settings, or any other textual content. Python can easily open, read, and write to these files.

Example 1: Writing to a Text File

Let’s start by writing a simple message to a text file. This example demonstrates the basic steps involved in opening a file, writing to it, and closing it.


# Create a file named "my_file.txt"
try:
    file = open("my_file.txt", "w")  # Open in write mode ("w")
    file.write("Hello, world!n")  # Write the string to the file
    file.write("This is a new line.n")
    file.close()  # Close the file
    print("Data written to my_file.txt")
except Exception as e:
    print(f"An error occurred: {e}")

Explanation:

  • We use the `open()` function to open a file named “my_file.txt” in write mode (“w”). If the file doesn’t exist, it will be created. If it does exist, its contents will be overwritten.
  • `file.write()` is used to write strings to the file. We use `n` to add a newline character, ensuring that each line is on a separate line in the file.
  • `file.close()` is crucial! It closes the file, releasing the resources and ensuring that the data is properly written to the disk. Failure to close files can lead to data corruption or incomplete writes.

Common Mistakes:

  • Forgetting to close the file: This can lead to data loss or corruption. Always use `file.close()` when you’re finished writing to the file.
  • Using the wrong mode: Using “w” when you intend to append to the file. Use “a” for append mode.

Data written to my_file.txt

Example 2: Reading from a Text File

Now, let’s read the contents of the “my_file.txt” file we just created.


try:
    file = open("my_file.txt", "r")  # Open in read mode ("r")
    content = file.read()  # Read the entire file content
    file.close()
    print("File content:n", content)
except FileNotFoundError:
    print("File not found.")
except Exception as e:
    print(f"An error occurred: {e}")

Explanation:

  • We use `open()` to open “my_file.txt” in read mode (“r”).
  • `file.read()` reads the entire content of the file as a single string.
  • We close the file.
  • We print the contents of the string.

Common Mistakes:

  • Not handling `FileNotFoundError`: If the file doesn’t exist, a `FileNotFoundError` will be raised. Catching and handling this error prevents the program from crashing.

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, which is often more efficient for large files.


try:
    file = open("my_file.txt", "r")
    for line in file:
        print("Line:", line.strip()) # strip() removes leading/trailing whitespace
    file.close()
except FileNotFoundError:
    print("File not found.")
except Exception as e:
    print(f"An error occurred: {e}")

Explanation:

  • We open “my_file.txt” in read mode (“r”).
  • We use a `for` loop to iterate through each line in the file.
  • `line.strip()` removes any leading or trailing whitespace (spaces, tabs, newlines) from each line, making the output cleaner.
  • We print each line.

Line: Hello, world!
Line: This is a new line.

Conclusion

This tutorial has covered the basics of reading and writing text files in Python. Remember to always handle potential errors (like `FileNotFoundError`) and to close your files properly. Experiment with different file names and content to solidify your understanding.

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.