READING AND WRITING TEXT FILES

Reading and writing text files in Python is straightforward using built-in file handling methods. You can use the open() function to open a file, read its contents, and write data to it. Here's how you can read and write text files in Python:

1. Reading Text Files:

To read the contents of a text file, you can use the open() function with the mode "r" (read mode). The read() method reads the entire file content as a string.

python
# Example: Reading a text file named "sample.txt" file_path = "sample.txt" # Open the file in read mode with open(file_path, "r") as file: file_content = file.read() print(file_content)

In the above example, we open the file "sample.txt" in read mode and read its entire content into the file_content variable. The with statement is used to ensure that the file is properly closed after reading.

2. Writing Text Files:

To write data to a text file, you can use the open() function with the mode "w" (write mode). The write() method is then used to write data to the file.

python
# Example: Writing to a text file named "output.txt" file_path = "output.txt" data_to_write = "Hello, World!\nThis is a new line." # Open the file in write mode with open(file_path, "w") as file: file.write(data_to_write)

In this example, we open the file "output.txt" in write mode and write the contents of the data_to_write variable to the file. The \n is used to add a new line in the text.

3. Appending Text to a File:

If you want to add data to an existing file without overwriting its content, you can use the "a" (append mode) when opening the file.

python
# Example: Appending to a text file named "output.txt" file_path = "output.txt" data_to_append = "\nThis line is appended." # Open the file in append mode with open(file_path, "a") as file: file.write(data_to_append)

The with statement automatically closes the file after writing or appending.

Remember to handle file operations carefully, and use appropriate exception handling in case of any errors (e.g., file not found, permissions issues, etc.). Also, ensure that you close the file properly after reading or writing by using the with statement, as demonstrated in the examples.

Using the file handling methods in Python, you can easily read data from existing text files and create, write, or append data to new or existing text files.