简体   繁体   中英

extract part of a filename python and insert into the MySQL DB

Want to extract the filename from a directory and insert it into MySQL DB.

with glob.glob could easily extract the full path and filename from the particular directory. I only need the 1st part of the filename. The part I want to omit is fixed, but the part I want to keep may change as it depends on the time stamp.

part of the code is like this:

for name in glob.glob(r'/home/PROJ/result/*fileinfo.csv'):
    print (name)
    filename = os.path.basename(name)
    print(filename)

    filetail = str("_fileinfo.csv")
    print(filetail)

Print out shows as

/home/PROJ/result/Line01-200213_1625_fileinfo.csv
Line01-200213_1625_fileinfo.csv
_fileinfo.csv
/home/PROJ/result/Line01-200215_1619_fileinfo.csv
Line01-200215_1619_fileinfo.csv
_fileinfo.csv 

I just want the 'lineNo-YYMMDD_hhmm' part as a filename. Omit the '_fileinfo.csv' part from the filename and store it in a file. Then insert in DB.

For extracting the part you want, you can strip out the filenames:

for name in glob.glob(r'/home/PROJ/result/*fileinfo.csv'):
    file_prefix = os.path.basename(name)[:-(len('fileinfo.csv')+1)]
    print(file_prefix)

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