Output CSV with file path and file contents

Say I have two files in a folder called “test”:

/Desktop/test/a.txt contains:

abc

123

/Desktop/test/b.txt contains:

def

456

I would like to produce a CSV file that contains:

Filepath_folder1,Filepath_folder2,Filename,content
Desktop,test,a.txt,[content]
Desktop,test,b.txt,[content]

Hi.

What have you tried so far? What code do you have?

Extending from @JeremyLT,

What language are you approaching this with?

I’m using bash.

I’ve done the following based on this example:

echo "Filename,Code"

files=$(ls)

for file in ${files[@]}; do
    echo -n $file,
    tr -d '\n' < $file
    echo ""
done

But I’m getting the following output:

Filename,Code

a.txt

b.txt,zsh: no such file or directory: a.txt\nb.txt

I’m also unsure how to separate the folders. I was planning to just split the names in Excel, but I was wondering if there’s a more effective way to do it.

This is the python solution:

import csv
from pathlib import Path

with open('big.csv', 'w', encoding='Latin-1') as out_file:
    csv_out = csv.writer(out_file)
    csv_out.writerow(['FileName', 'Content'])
    for fileName in Path('.').resolve().glob('**/*.txt'):
        lines = [ ]
        with open(str(fileName.absolute()),'rb') as one_text:
            for line in one_text.readlines():
                lines.append(line.decode(encoding='Latin-1',errors='ignore').strip())
        csv_out.writerow([str(fileName),' '.join(lines)])