Skip to content

Python write to text file

  • by

To write data to a text file in Python, you can use the built-in open() function with the mode set to 'w' (write mode) or 'a' (append mode).

Writing to a text file in Python means that you are creating or modifying a text file by adding new content to it. Python provides built-in functions and methods to work with files, allowing you to open, read, write, and close files.

The syntax for writing to a text file in Python using the open() function is as follows:

with open(file_path, mode) as file:
    file.write(data_to_write)

Here’s an example of how to do it:

Writing to a new file (overwrite if exists):

file_path = 'example.txt'
data_to_write = "Hello, this is some text that will be written to the file."

# Open the file in write mode ('w')
with open(file_path, 'w') as file:
    file.write(data_to_write)

Appending to an existing file:

file_path = 'example.txt'
data_to_append = "\nThis line will be appended to the file."

# Open the file in append mode ('a')
with open(file_path, 'a') as file:
    file.write(data_to_append)

In both cases, the with open() statement ensures that the file is properly closed after writing, even if an exception occurs during the process.

If the file does not exist, the 'w' mode will create a new file, while the 'a' mode will create one if it doesn’t exist or append to it if it does. Be careful with the 'w' mode, as it will overwrite the entire contents of the file if it exists.

Python write-to-text file example

Here’s a simple example of writing a text file in Python:

# File path
file_path = 'example.txt'

# Data to write to the file
data_to_write = """Hello, this is some text that will be written to the file.
This is another line.
And this is the last line.
"""

# Open the file in write mode ('w')
with open(file_path, 'w') as file:
    # Write the data to the file
    file.write(data_to_write)

# Confirming the write operation
print("Data has been written to the file.")

Output:

Python write to text file

Remember to handle exceptions appropriately when dealing with file operations to ensure the program behaves gracefully in case of any errors.

Here’s the previous example with added exception handling:

file_path = 'example.txt'
data_to_write = "Hello, this is some text that will be written to the file."

try:
    # Open the file in write mode ('w')
    with open(file_path, 'w') as file:
        # Write the data to the file
        file.write(data_to_write)
    print("Data has been written to the file.")
except FileNotFoundError:
    print("Error: The file or path could not be found.")
except PermissionError:
    print("Error: You do not have permission to write to the file.")
except Exception as e:
    print("An unexpected error occurred:", e)

By handling exceptions, your program can provide informative feedback to users or take alternative actions if necessary, preventing the program from crashing abruptly.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading