Open In App

Append Text or Lines to a File in Python

Last Updated : 28 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Appending text or lines to a file is a common operation in programming, especially when you want to add new information to an existing file without overwriting its content. In Python, this task is made simple with built-in functions that allow you to open a file and append data to it. In this tutorial, we’ll explore what it means to append text or lines to a file and provide examples of both operations in Python.

What is Append Text or Lines to a File?

Appending text or lines to a file involves adding new content to the end of an existing file. It is a useful operation when you want to update or extend the information in a file without losing the existing data. Python provides the open() function to open a file and the write() method to add text, and the write() or writelines() methods to append lines to a file.

How To Append Text Or Lines To A File In Python?

Below, are the example of How To Append Text Or Lines To A File In Python.

Append Text to a File

In this example, the Python function `append_text_to_file` appends the given `text_to_append` to the specified `file_path`. It opens the file in ‘a’ (append) mode, writes the text followed by a newline, and prints a success message. If any error occurs during the process, it prints an error message. The example usage demonstrates appending the specified text to the file ‘example.txt’.

Python3




def append_text_to_file(file_path, text_to_append):
    try:
        with open(file_path, 'a') as file:
            file.write(text_to_append + '\n')
        print(f"Text appended to {file_path} successfully.")
    except Exception as e:
        print(f"Error: {e}")
  
# Example Usage
file_path = 'example.txt'
text_to_append = 'This is a new line of text.'
append_text_to_file(file_path, text_to_append)


Output

Text appended to test.txt successfully.

.txt File

This is a new line of text.

Append Lines to a File

In this example, Python function `append_lines_to_file` appends the given list of `lines_to_append` to the specified `file_path`. It opens the file in ‘a’ (append) mode, joins the lines with newline characters, writes them to the file, and prints a success message. If any error occurs during the process, it prints an error message.

Python3




def append_lines_to_file(file_path, lines_to_append):
    try:
        with open(file_path, 'a') as file:
            file.write('\n'.join(lines_to_append) + '\n')
        print(f"Lines appended to {file_path} successfully.")
    except Exception as e:
        print(f"Error: {e}")
  
# Example Usage
file_path = 'example.txt'
lines_to_append = ['Geek 1', 'Geek 2', 'Geek 3']
append_lines_to_file(file_path, lines_to_append)


Output

Lines appended to example.txt successfully.

.txt File

Geeks 1
Geek 2
Geek 3

Conclusion

Appending text or lines to a file in Python is a straightforward process using the the with the ‘a’ (append) mode. This allows you to update files without losing existing data, making it a valuable technique for various programming tasks. Always handle file existence appropriately, and be cautious about potential exceptions during file operations.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads