Adding Content to the First Line of Text Files with Python

This article delves into a Python script designed to add a predefined string to the first line of every text file in a given directory.

Script Functionality

The primary function of this script is to prepend a specific line of text to each .txt file in a specified directory. This can be particularly useful for adding headers, tags, or any form of standardized information to a batch of files.

Importing Necessary Module

import os

The script begins by importing the os module, which is essential for interacting with the file system.

Defining the Function to Add Content

def add_content_to_file(filename):
    """Add 'Content needs to add' to the first line of the file."""
    # File reading and writing logic here

This function, add_content_to_file, is responsible for the core operation of the script—adding a predefined string ("Content needs to add") to the first line of the given file.

Reading and Modifying File Content

with open(filename, 'r', encoding='utf-8') as file:
    content = file.readlines()

content.insert(0, "Content needs to add")

The script reads the original content of the file and uses the insert method to add the new content at the beginning of the list of lines.

Writing the Modified Content Back to the File

with open(filename, 'w', encoding='utf-8') as file:
    file.writelines(content)

After modifying the content, the script writes it back to the same file. This overwrites the file with the updated content.

The Main Function

def main():
    directory = '/content/add'
    # Directory processing logic here

The main function sets the target directory and iterates over each file within it, applying the add_content_to_file function to each .txt file.

Processing Each File in the Directory

for filename in os.listdir(directory):
    if filename.endswith('.txt'):
        full_path = os.path.join(directory, filename)
        # Error handling and file processing here

The script loops through all files in the specified directory, checking for text files and then calling add_content_to_file on each.

Error Handling

try:
    add_content_to_file(full_path)
    print(f"Added content to {filename}")
except Exception as e:
    print(f"Failed to add content to {filename}. Error: {e}")

Error handling is implemented to catch and report any issues that occur during file processing.

Script Execution

if __name__ == "__main__":
    main()

This conditional ensures that main is called only when the script is executed as a standalone program.

Conclusion

This Python script showcases the ease with which text files can be manipulated to add specific content. It’s a handy tool for batch processing files, especially when you need to insert headers, metadata, or any standard information across multiple documents. Python’s straightforward syntax and powerful file handling capabilities make it an ideal choice for such tasks, offering automation and efficiency.