I have two directories filled with .txt files, with each .txt file containing a list of terms separated by commas. Each directory has files with the same names, but the contents of each file may be different. I want to concatenate each file with the same name, but omit duplicate tags. Can you provide a python script to do this?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure, here is a simple script that could assist you with this task. This script assumes that the directories are in the same parent directory and named 'dir1' and 'dir2'. You can change these according to your needs. The resulting files with unique terms will be stored in a new directory named 'output'.
python
import os
import csv
# Define directories
dir1 = 'dir1'
dir2 = 'dir2'
output_dir = 'output'
# Create output directory if it does not exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Get the list of text files
txt_files = [f for f in os.listdir(dir1) if os.path.isfile(os.path.join(dir1, f)) and f.endswith('.txt')]
# Process each file
for txt_file in txt_files:
# Create sets to store unique terms
terms = set()
# Read and process the first file
with open(os.path.join(dir1, txt_file), 'r') as f:
reader = csv.reader(f)
for row in reader:
terms.update(row)
# Read and process the second file
with open(os.path.join(dir2, txt_file), 'r') as f:
reader = csv.reader(f)
for row in reader:
terms.update(row)
# Write the result to the output file
with open(os.path.join(output_dir, txt_file), 'w') as f:
writer = csv.writer(f)
writer.writerow(list(terms))
This script will read each file, turn the list of terms into a set (which automatically removes duplicates), and then write the set back to a new file in the output directory. Note that the order of terms in the output may not be the same as the input, as sets do not preserve order.
Please ensure the directories and files can be accessed (correct path, read/write permissions etc.) before running the script.