file renaming using python

2019-09-03 14:45发布

问题:

I am trying to rename a file in which it is auto-generated by some local modules but I was wondering if using os.listdir is the only way for me to filter/ narrow down this file. This file will always be generated before it is removed and the code will generate the next one (still in the same directory) based on the next item in list.

Basically, whenever this file is generated, it comes in the following file path: /user_data/.tmp/tempLibFiles/2015_03_16_192212_182096.con

I had only wanted to rename the 2015_03_16_192212_182096 into connectionFile while keeping the rest the same.

回答1:

You can also use the glob module to narrow down the list of files to the one that matches a particular pattern. For example:

import glob
files = glob.glob('/user_data/.tmp/tempLibFiles/*.con')