Skip to main content

How to append to a text file in Python

How to append to a text file in Python.

Here's a step-by-step tutorial on how to append to a text file in Python:

Step 1: Open the File

To start appending data to a text file in Python, you first need to open the file using the built-in open() function. This function accepts two arguments: the file name/path and the mode in which you want to open the file. In this case, we want to open the file in append mode, so we'll pass the mode as 'a'.

file = open('filename.txt', 'a')

Step 2: Write Data to the File

Once the file is opened in append mode, you can use the write() method to write data to the file. The write() method takes a string argument, so make sure to convert any other data types to a string before writing.

file.write('Hello, World!\n')

Step 3: Close the File After you finish appending data to the file, it's important to close the file to free up system resources. You can close the file using the close() method.

file.close()

Putting it all together, here's a complete example that appends multiple lines to a text file:

# Open the file in append mode
file = open('filename.txt', 'a')

# Write multiple lines to the file
file.write('Hello, World!\n')
file.write('This is a new line.\n')
file.write('Appending more data.\n')

# Close the file
file.close()

Note: It's a best practice to use the with statement when working with files in Python. The with statement automatically takes care of closing the file even if an exception occurs. Here's an example:

with open('filename.txt', 'a') as file:
file.write('Hello, World!\n')
file.write('This is a new line.\n')
file.write('Appending more data.\n')

That's it! You now know how to append data to a text file in Python.