0

Hello I am trying to write every odd and then even filename from a Folder to a text file.

import os

TXT = "C:/Users/Admin/Documents/combine.txt"

# Collects Files
with open(TXT, "w") as a:
    for path, subdirs, files in os.walk(r'C:\Users\Admin\Desktop\combine'):
       for filename in files:
         f = os.path.join(path, filename)
         a.write("file '" + str(f) + "'" + '\n') 
example filenames: 01, 02, 03, 04, 05, 06, 07, 08, 09 .png

wanted results:
file 'C:\Users\Admin\Desktop\combine\01.png'
file 'C:\Users\Admin\Desktop\combine\03.png'
file 'C:\Users\Admin\Desktop\combine\05.png'
file 'C:\Users\Admin\Desktop\combine\07.png'
file 'C:\Users\Admin\Desktop\combine\09.png'
file 'C:\Users\Admin\Desktop\combine\02.png'
file 'C:\Users\Admin\Desktop\combine\04.png'
file 'C:\Users\Admin\Desktop\combine\06.png'
file 'C:\Users\Admin\Desktop\combine\08.png'
Dustin N
  • 19
  • 3
  • Seems like `files[0::2]` and `files[1::2]` could help, assuming that you'll always ever number in your files list – Mitchell van Zuylen Dec 04 '22 at 10:03
  • 1
    If you just want the files in the folder, why are you using `os.walk`? Wouldn't it be much simpler to just [`listdir`](https://docs.python.org/3/library/os.html#os.listdir) the directory you're interested in? – Tomerikoo Dec 04 '22 at 10:05

1 Answers1

1

As suggested by Mitchell van Zuylen, and Tomerikoo, you could use slicing and listdir to produce your desired output:

Code:

import os

N = 2  # every 2nd filename

combine_txt = "C:\Users\Admin\Documents\combine.txt"
folder_of_interest = 'C:\Users\Admin\Desktop\combine'

files = sorted(os.listdir(folder_of_interest))
files = [f for f in files if f.endswith('.png')]  #only select .png files

with open(combine_txt, "w") as a:
    for i in range(N):
        for f in files[i::N]:
            a.write(f"file '{folder_of_interest}\\{f}'\n")

Output:

combine.txt

file 'C:\Users\Admin\Desktop\combine\01.png'
file 'C:\Users\Admin\Desktop\combine\03.png'
file 'C:\Users\Admin\Desktop\combine\05.png'
file 'C:\Users\Admin\Desktop\combine\07.png'
file 'C:\Users\Admin\Desktop\combine\09.png'
file 'C:\Users\Admin\Desktop\combine\02.png'
file 'C:\Users\Admin\Desktop\combine\04.png'
file 'C:\Users\Admin\Desktop\combine\06.png'
file 'C:\Users\Admin\Desktop\combine\08.png'

Note:

You can change N = 2 to N = 3 to list every 3rd filename in the same way.

ScottC
  • 3,941
  • 1
  • 6
  • 20
  • From the `listdir` docs (linked in a comment above): *"The list is in __arbitrary order__"* – Tomerikoo Dec 04 '22 at 11:29
  • 1
    When I tested - it seemed to work. But have now **updated the code** to sort the filenames just in case. The output is still the same. – ScottC Dec 04 '22 at 11:40