简体   繁体   中英

How to write the number of lines of an .txt output before it's first line?

I am using the code below to generate an output with filenames saved in a certain directory.

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)}\n')
         count += 1

I am trying now to write the number of lines before the first line. with the code above I obtain:

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

while what i need is:

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

with open("bionaplsatfiles.dat", "w") as a:
    count = 0
    txt = ''
    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)
            txt += f'{count} {str(f)}\n'
            count += 1
    a.write(f'{count}\n{txt}')

You don't need the variable count , just use len and pass files as parameter:

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'):
       a.write(f'{len(files)}\n')
       for index, filename in enumerate(files):
         f = os.path.join(filename)
         a.write(f'{index} {str(f)}\n')

I also refacted a bit your code to take advantage of enumerate

Hope this helps:

import os  

with open("bionaplsatfiles.dat", "w") as a:
    count = 0
    file_list = []
    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)
         file_list.append(f'{count} {str(f)}\n')
         count += 1
    a.write(str(count))
    a.write("\n")
    for i in file_list:
        a.write(i)

Get a list of file names, measure and record its length, then write the names:

DIR = r'D:\Bionapl_Nicolas\testKB\vtu_files\output_Sn')
names = [os.path.join(filename) for _, _, files in os.walk(DIR) 
                                for filename in files]

with open("bionaplsatfiles.dat", "w") as a:
    a.write(f'{len(names)}\n')
    for count, name in enumerate(names):
        a.write(f'{count} {name}\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM