简体   繁体   中英

Python - Read file names in directory, write twice to text file (one without file extensions), and separate with pipe

I have a directory (c:\\temp) with some files:

a.txt  
b.py  
c.html

I need to read all of the files in a directory and output it to a text file. I've got that part handled (I think):

WD = "c:\\temp"

import glob

files = glob.glob('*.*')
with open('dirList.txt', 'w') as in_files:
    for eachfile in files: in_files.write(eachfile + '\n')

I need the output to look like:

a|a.txt  
b|b.py  
c|c.html

I'm not quite sure where to look next.

I'd split the file name by . and take the first part:

for eachfile in files:
    in_files.write('%s|%s\n' % (eachfile.split('.')[0], eachfile))

You have almost solved your problem. I am not quite sure where you are getting stuck. If all you need to write is the file name (without extension) followed by | then you just need to update your code as this:

import glob

files = glob.glob('*.*')
with open('dirList.txt', 'w') as in_files:
    for eachfile in files:
        file_name_without_extension = eachfile.split(".")[0]
        in_files.write( file_name_without_extension + "|" + eachfile 
+ '\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