0

I have multiple .txt files in different levels of subdirectory. All txt files are in the final iteration, that is, there is no level with both .txt files and further directories. I want to concatenate them all into one new text file, but can't find a simple way to go through all the subdirectories.

A command I've found, that is to be entered into the python command line terminal thus:

$ cat source/file/*.txt > source/output/output.txt

But I am not sure how I could make this iterate over multiple subdirectories. (I am a real beginner with python, there seems to be some confusion. Is this not a python command? The source I found it from claimed it was...)

Henry Brice
  • 280
  • 1
  • 2
  • 18
  • 2
    I fail to see how Python is related to this? – Jon Clements Apr 22 '14 at 13:55
  • 1
    `cat` isn't a windows utility. – Hunter McMillen Apr 22 '14 at 13:56
  • If you're talking about Cygwin in Windows 7, `find /source/dir -name *.txt -exec cat {} >> /destination/dir/output.txt \;` should work. – Phylogenesis Apr 22 '14 at 13:58
  • 1
    i would prefer `find source_dir -name "*.txt" -type f | xargs cat > output.file.txt` (does not start a new cat on every file) – m.wasowski Apr 22 '14 at 14:04
  • 1
    @Henry please make it clear, if you are looking for cygwin solution, or pure windows command line (where there is no `cat`). – m.wasowski Apr 22 '14 at 14:05
  • If you wanted a python solution `import fileinput;with open('output.txt', 'w') as out:out.writelines(fileinput.input())`. – Bakuriu Apr 22 '14 at 14:10
  • `cat` is the least important problem here, as `type` does (almost?) the same thing on Win. – BartoszKP Apr 22 '14 at 14:24
  • I apologise if there is a misunderstanding, I am only a beginner with python. I thought that the python command line could take cat, I understand from the responses that this is not a python command at all? This was initially written as a question about python, someone edited it to take out all python references, which seems to be the source of some of the confusion... – Henry Brice Apr 22 '14 at 15:30

1 Answers1

0

You could build them using a python script using something like:

file_list = ['c:\data.txt', 'c:\folder1\data.txt']

for everything in file_list:
    f = open(everything)
    for line in f.readlines():
        print line

Call the script from cmd e.g. \python.exe 'buildtxtfiles.py'

kezzos
  • 3,023
  • 3
  • 20
  • 37
  • Would the file_list only have to include the top folder, or would I have to list all directories and subdirectories? There are thousands of subdirectories, I am looking for a solution that can go through them for me, rather than having to define a list in advance... – Henry Brice Apr 22 '14 at 15:34