{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Newlines to commas\n", "----\n", "\n", "Recursively modify the content of `.txt` files in the specified directory and its subdirectories by replacing newlines with commas and spaces. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"\"\"\n", "This script is designed to process all text files within a specified directory\n", "and its subdirectories. It modifies the content of each text file by replacing\n", "newlines with a comma followed by a space.\n", "\n", "Functions:\n", " process_directory(directory): Recursively processes all '.txt' files in the given directory.\n", "\n", "Args:\n", " directory (str): The path to the directory containing the text files to be processed.\n", "\n", "Usage:\n", " Set the 'directory_path' variable to the path of the target directory and run the script.\n", " The script will modify all '.txt' files within this directory and its subdirectories.\n", "\"\"\"\n", "from pathlib import Path\n", "\n", "def process_directory(directory):\n", " \"\"\"\n", " Process all '.txt' files in the given directory, replacing newlines with a comma and space.\n", "\n", " Parameters:\n", " - directory (str): The path to the directory to process.\n", " \"\"\"\n", " # Create a Path object for the directory\n", " path = Path(directory)\n", " \n", " # Use glob pattern to match all .txt files recursively\n", " for file_path in path.rglob('*.txt'):\n", " # Read the content of the file\n", " with open(file_path, 'r') as file:\n", " content = file.read()\n", " \n", " # Replace newline with a comma and space\n", " modified_content = content.replace('\\n', ', ')\n", " \n", " # Write the modified content back to the file\n", " with open(file_path, 'w') as file:\n", " file.write(modified_content)\n", "\n", "# Directory path\n", "directory_path = r'C:\\Users\\kade\\Desktop\\training_dir_staging'\n", "\n", "# Recursively process the directory and its subdirectories\n", "process_directory(directory_path)" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }