Search code examples
pythonextractfilenames

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.


Solution

  • 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)