Page Content

Tutorials

How To Read and Write Text Files In Python With Example

Read and Write Text Files

Read and Write Text Files
Read and Write Text Files

A popular method for permanently storing data in Python is to use text files, which let applications save and access data long after they have completed running. Simple text characters are found in text files. They are usually regarded as a series of lines, with each line consisting of a series of ASCII or UNICODE characters that are saved on permanent storage media. The End of Line (EOL) character, which is ‘n’ (the newline character) in Python by default, is frequently used to end each line. Python’s default character encoding is ASCII. Although text files can be read by humans, they are essentially just collections of data.

Opening the file, reading or writing to it, and then closing it are the three basic stages involved in working with files in Python. To open files, Python has the built-in open() method. Most often, the filename and the mode are the two arguments passed to the open() function. One string that indicates how the file will be used for example, for reading or writing is called the mode parameter. The file object, also known as a file handler, that is returned when a file is opened with open() offers ways to access the file.

Here are some common modes for opening text files:

  • ‘r’ (read): The command opens the file alone for reading. If there is no mode given, this is the default mode. A Python error will be raised if the file is not found.
  • ‘w’ (write): Generates a writing file. Files are created if they don’t already exist.Any existing file is overwritten.
  • ‘a’ (append): Use ‘a’ to add files. If the file already exists, it adds new data. Files are created if they don’t already exist.
  • ‘x’ (create): The provided file is created, but if the file already exists, an error is returned.
  • ‘+’ (update): This opens the file for writing and reading; it updates. These modes can be used in conjunction with others, like ‘r+’ (read and write, error if file doesn’t exist) or ‘w+’ (write and read, overwrites existing file or creates new one).
  • ‘t’ (text): The default text mode is specified via the ‘t’ (text) command. You can read and write strings in text mode. Line ends corresponding to a given platform are changed to ‘n’ while reading and vice versa when writing.

Once actions are complete, you should use the close() method to close the file. A closed file must be opened again in order to be read from or written to.

When working with file objects, the with statement is a superior approach. Even in the event of an exception, the benefit is that the file is automatically closed when the code block is exited.

Reading from a Text File

The usual way to read from a text file is to open it in read mode (‘r’). Python has a number of ways to read information from a file object:

  • read(): Retrieves the file’s complete contents as a single string. You have the ability to read only a specific amount of characters by passing in a size argument.
  • readline(): Returns a string after reading a single line from the file, including the newline character (n) if it exists. Subsequent lines are read when it is called repeatedly. At the conclusion of the file, an empty string (”) is returned.
  • readlines(): Acquires a list of strings, each of which is a line from the file’s contents (including newline characters), after reading every line from the file.
  • Iteration: The most popular and frequently effective method for reading lines from a text file is to use a for loop to traverse directly over the file object. In terms of memory use, this automatically reads one line at a time.

Example of Reading:

Assume that the file greet.txt contains the text “Hello, world!”

Example:

# Using read() to read the entire file
try:
    with open("greet.txt", "r") as f: 
        data = f. read() 
        print("Contents of greet.txt:")
        print(data)
except File Not Found Error: 
    print("Error: greet.txt not found.")
print("-" * 20)
# Using iteration to read line by line
# Let's assume a file named 'multi line.txt' exists with multiple lines
# Example content for multi line.txt:
# First line.
# Second line.
# Third line.
try:
    # In a real scenario, you would ensure multi line.txt exists
    # For this example, we'll simulate it or assume its existence
    print("Reading multi line.txt line by line:")
    with open("multi line.txt", "r") as f: 
        for line in f: 
            print(line, end='') 
    print("\n" + "-" * 20)
except File Not Found Error:
     # If multi line.txt does not exist, we'll see this message.
    print("Error: multi line txt not found. Cannot demonstrate line by line reading.")
    print("-" * 20)

# Using read lines() to get a list of lines
# Assuming multi line.txt exists
try:
    with open("multi line.txt", "r") as f:
        lines = f. read lines() 
        print("Contents of multi line.txt as a list of strings:")
        print(lines)
    print("-" * 20)
except FileNotFoundError:
     # If multi line.txt does not exist, we'll see this message.
    print("Error: multi line.txt not found. Cannot demonstrate read lines().")
    print("-" * 20)

Note: Managing File Not Found Error when trying to read an invalid file. A try-except block is used in the aforementioned instances for this reason.

Writing to a Text File

Open a text file in either write mode (‘w’) or append mode (‘a’) to write to it.

  • If a file is present, it will be overwritten in “w” mode.
  • If data is present, it will be appended to the end of the file in “a” mode.

The following techniques are available for writing to an opened file object:

  • Write the given string to the file using the write(string) function. This approach does not add a newline character (\n) automatically. If you wish to begin a new line, you must include ‘n’ in the string explicitly. The number of written characters is returned by the procedure.
  • Write a string sequence to the file using write lines(list of strings). Newlines are not automatically added between the elements in the sequence using this method either. If you want newline characters in the list’s strings, you must make sure they are there.
  • The print() function’s output can be redirected to a file by providing the optional file argument, as shown in print( file=file object). Although the end option allows you to regulate it, print(), in contrast to write(), does by default append a newline character at the conclusion.

Example of Writing:

# Using write() to write strings to a file
# Using 'w' mode will overwrite the file if it exists
with open("output.txt", "w") as f: 
    f. write("This is the first line.\n") # Need to explicitly add newline 
    f. write("This is the second line.")
    # File is automatically closed when exiting the 'with' block 
# Using 'a' mode to append to the file
with open("output.txt", "a") as f: 
    f. write("\n This line is appended.") # Add newline before appending for clarity
# Using print() with the file argument
with open("print output.txt", "w") as f:
    print("Line 1 from print.", file=f) # print() adds newline by default 
    print("Line 2 from print.", file=f)
print("Data written to output.txt and print output.txt.")
# You can verify the contents by reading them back
print("-" * 20)
print("Reading output.txt:")
with open("output.txt", "r") as f:
    print(f. read())
print("-" * 20)
print("Reading print output.txt:")
with open("print output.txt", "r") as f:
    print(f. read())

It is important to close files after writing in order to verify that the text is preserved correctly. The with statement takes care of this on its own.

All things considered, Python’s built-in functions and techniques offer simple approaches to working with text files, facilitating the exchange and maintenance of textual data. The secret to efficient file handling in Python is knowing the various file modes and how functions like read(), write(), and print (file=) behave.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index