File size: 2,524 Bytes
6776f94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
{
 "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
}