Reading and Writing Text files in Python


File handling is a fundamental aspect of programming, allowing you to interact with external files to store, retrieve, and manipulate data. In this article, we'll delve into the world of reading and writing text files in Python, providing you with the knowledge and tools to effectively manage your data.

 

Reading Text Files

 

Reading data from a text file is a common operation in programming. Python provides an easy-to-use mechanism for accomplishing this task.

 

Using the open() Function

 

To read a text file, you can use the built-in open() function. This function takes two arguments: the file name/path and the mode in which you want to open the file. For reading text files, you'll use the mode 'r'.

# Opening a text file for reading

file_path = 'sample.txt'



with open(file_path, 'r') as file:

    content = file.read()

    print(content)

In the code snippet, the variable file_path is a string that represents the path to a text file you want to read. The file path indicates the location of the file on your computer's file system.

 

Defining the file path depends on the location of the file you want to access and the type of path you want to use (absolute or relative). Here are a few ways to define a file path

 

Absolute File Path

An absolute file path specifies the full path from the root directory to the file. It starts from the drive letter (on Windows) or the root directory (on Unix-like systems). Here are examples for both operating systems:

 

On Windows

file_path = 'C:\\Users\\Username\\Documents\\sample.txt'

 

On Unix

file_path = '/home/username/Documents/sample.txt'

 

Relative File Path

A relative file path is defined relative to the current working directory of your program. It specifies the path to the file starting from the directory where your program is located.

For example, if your program is located at /home/username/Code/ and the file you want to read is in /home/username/Documents/, you can specify a relative path like this:

file_path = '../Documents/sample.txt'

 

The with statement is used to open the file located at the specified file_path for reading ('r' mode). The file.read() method reads the entire content of the file and stores it in the content variable. The printed output will display the content of the file.

 

You can replace 'r' with other modes depending on what you intend to do with the file. Here are some common file modes:

'r': Read mode (default). Opens the file for reading.

'w': Write mode. Opens the file for writing. Creates a new file or truncates an existing file.

'a': Append mode. Opens the file for writing. Creates a new file or appends to an existing file.

 

It's important to ensure that the file path is accurate and correctly represents the location of the file you intend to read. The format of the file path will depend on the operating system you are using.

 

Reading Line by Line

You can also read a text file line by line using a loop. This is especially useful for larger files that might not fit into memory all at once.

 

Let's assume we have a file named "sample.txt" with the following content:

Line 1: This is the first line.

Line 2: Here's the second line.

Line 3: And this is the third line.

 

# Reading a text file line by line

with open(file_path, 'r') as file:

    for line in file:

        print(line.strip())  # Strip to remove extra newline characters

Output

Line 1: This is the first line.

Line 2: Here's the second line.

Line 3: And this is the third line.

 

Writing Text Files

 

Writing data to a text file is equally important, as it allows you to store information generated during program execution.

 

Using the open() Function for Writing

To write to a text file, you need to use the 'w' mode with the open() function. If the file already exists, this mode will overwrite its contents. If the file doesn't exist, a new file will be created.

# Writing to a text file

output_path = 'output.txt'

data_to_write = "Hello, this is a line to write."


with open(output_path, 'w') as file:

    file.write(data_to_write)

After running this code, a file named "output.txt" will be created with the content "Hello, this is a line to write."

 

Appending to a Text File

If you want to add content to an existing file without overwriting it, you can use the 'a' mode.

# Appending to a text file

data_to_append = "\nThis line is appended."



with open(output_path, 'a') as file:

    file.write(data_to_append)

After running this code, the "output.txt" file will be updated to have the following content:

Hello, this is a line to write.

This line is appended.

 

Handling Exceptions

When working with files, it's crucial to handle exceptions that might occur, such as file not found errors or permission issues.

try:

    with open(file_path, 'r') as file:

        content = file.read()

        # Process the content

except FileNotFoundError:

    print("File not found.")

except PermissionError:

    print("Permission denied.")

except Exception as e:

    print("An error occurred:", str(e))

This code will print "File not found." since the specified file "non_existent_file.txt" does not exist.

       

Summary

 

Mastering file handling in Python is an essential skill for any programmer. By understanding how to read and write text files, you can effectively manage data, create and update configurations, and handle various data processing tasks. Remember to close the file after you're done using it, and always implement error handling for robust code.



Thanks for feedback.



Read More....
Arrays and Lists in Python
Python Iterators
Lambda or Anonymous Functions in Python
Most common built-in methods in Python
Python Decorators
Python Dictionaries