Python Forum

Full Version: error merge text files
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!

I want to merge all of the txt-files I have in a specific folder on my computer. I looked it up and apparently you have to use the following code/command in Powershell:
copy *.txt newfile.txt
However, when I give this command, all I get is "newfile.txt" that only contains a copy of the very first txt-file in my folder, but nothing else. So it didn't really work when I tried to merge them.

Is there a way to fix this issue or an easy way to do it in Python? I looked it up, but so far I only found code snippets in which you have to type all of the filenames. Because it's more than 200 files with completely different names, this isn't a good solution for me.

Thank you in advance for your kind help!
see this post which I just made to see how to get a list of files
https://python-forum.io/Thread-read-csv-...ns-missing
after that, all you need to do is add merge code.
@Larz60+

Thank you!
A big pitfall is, that the files are not in sorted order.
What happens if you have the wrong assumptions about glob: https://science.slashdot.org/story/19/10...ed-studies

from pathlib import Path


def get_sorted_file_list(root, pattern='*.txt', recursive=False):
    if recursive:
        extension = '**/' + pattern
    for file in sorted(Path(root).glob(pattern)):
        if file.is_file():
            yield file


text_files_sorted = list(get_sorted_file_list(root='.', pattern='*.txt', recursive=False))
The result is ordered lexical.

I guess it's important for your task, that the order is right.