How to write file names which are in a certain directory + index of each line?

Viewed 75

I am trying to get the file names which are in a folder wrote into an output file with the index of each line. I am using the code below to write the filenames:

import os

with open("bionaplsatfiles.dat", "w") as a:
    for path, subdirs, files in os.walk(r'D:\Bionapl_Nicolas\testKB\vtu_files\output_Sn'):
       for filename in files:
         f = os.path.join(filename)
         a.write(str(f) + os.linesep)

I am getting the result below:

Sat_t0.txt
Sat_t1.txt
Sat_t2.txt
Sat_t3.txt
Sat_t4.txt
Sat_t5.txt

But what I need is :

0   Sat_t0.txt
1   Sat_t1.txt
2   Sat_t2.txt
3   Sat_t3.txt
4   Sat_t4.txt
5   Sat_t5.txt

What should I add to my code to get the index column? Thank you

2 Answers

Use enumerate:

import os

with open("bionaplsatfiles.dat", "w") as a:
    for path, subdirs, files in os.walk(r'D:\Bionapl_Nicolas\testKB\vtu_files\output_Sn'):
       for index, filename in enumerate(files): # FIX
         f = os.path.join(filename)
         a.write(str(f) + os.linesep)

See the official documentation.

You can simply use a counter variable. The code might look like this:

import os

with open("bionaplsatfiles.dat", "w") as a:
    count = 0
    for path, subdirs, files in os.walk(r'D:\Bionapl_Nicolas\testKB\vtu_files\output_Sn'):
       for filename in files:
         f = os.path.join(filename)
         a.write(f'{count} {str(f)}{os.linesep}')
         count += 1
Related