0

I'm trying to find the easiest way to add os.walk to a script.
This script is a merger, it reads all text files and merges them into 1 text file.

import glob

read_files = glob.glob("Original/Files/*.txt")

with open("Merge/(2).txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())

This works great: it merges all files together but having issues with the way it merges the files, because it doesn't merge them in the same order as they are in the folders.

I tried several different ways to add os.walk ('.') and I can't figure it out.
I do know about this './../.../' but this only scans up to that folder count.

I have several other small python scripts that I would like to add a os.walk to. I'm trying to learn the easiest way to add something like os.walk to all my scripts.

I am very new to python so this is not easy for me.
I tried this:

import os

for read_files in os.walk('.'):
 with open("Merge/(2).txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())
        

But am not sure how to connect them, that is what I'm trying to learn so that I can practice more on my other smaller scripts.

On several attempts I did managed to get it to generate the (2).txt but it was blank.

martineau
  • 119,623
  • 25
  • 170
  • 301
JR Santos
  • 137
  • 1
  • 11
  • What happens when you run your script? – ewokx Feb 21 '22 at 23:41
  • @ewong the cmd opens and closes and that's it, I did manage using the `read_files = glob.glob("./.*.txt")` to read a txt file but the text file was in a folder outside this testing folder, example `main folder/file.txt`, and inside main folder I have `Merger folder/merger.py` and inside merger folder I have 5 folders loaded with txt files and some how I got it to read the file.txt found in the main folder...lol – JR Santos Feb 21 '22 at 23:52
  • I meant what happens when you run the 2nd script? Please read up on ```os.walk()``` in https://docs.python.org/3/library/os.html. – ewokx Feb 22 '22 at 00:24
  • The results obtained from `os.walk()` will not be ordered the same way you *think* they are ordered in folders either. The order of files is arbitrary, but the tools you use to view them (or your OS) may make them seem to be ordered in some fashion. – martineau Feb 22 '22 at 01:51

0 Answers0