简体   繁体   中英

How to prepend the prefix “_” to all files in a folder, in a list of files [Python]

Every day I am running my script which outputs a log file. I have an external Hive table reading all files in the folder not having the prefix "_". Therefore, whenever I am running my script I would need to prepend "_" to all files in the folder which end with ".log" and do not have the "_" prefix already.

My folder structure is like this.

 -output
   -_data-2020-04-10.log
   -data-2020-04-11.log

And my code is currently like this

 if __name__ == "__main__"
     df = fetch_todays_data() #Returns dataframe
     if not [f for f in os.listdir(dataPath) if not f.startswith('_') and f.endswith(".log")] == []:
            fileset = [f for f in os.listdir(dataPath) if not f.startswith('_') and f.endswith(".log")]
            for f in fileset:         
                 #### prepend "_" to all files.

     dataframe_to_json_log(output_path+/'data-{}'.format(datetime.date.today())) #Help function that transforms dataframe to json_blob in output folder

How do I correctly prepend "_" to all files in fileset ?

EDIT:

I did not know the meaning of append, it should be prepend.

Similar to what TheMechanist has but without affecting files that already have the "_" prefix:

import glob, os
fileset = [f for f in glob.glob("*.log") if not f.startswith('_')]
for f in fileset:
   os.rename(f, "_" + f)

You can use glob:

from os.path import basename
import glob, os
path = 'mypath'
os.chdir(path)
basename(path)
for file in glob.glob("*.log"):
     os.rename(basename, "_"+basename)

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