找出文件名具有一定格式的文件:
import os
import re
path = "/root"
targetDir='/root/result'
def getfilelist(strn):
names=[]
for dirpath, dirnames, filenames in os.walk(path):
for filepath in filenames:
# image_name=os.path.join(dirpath, filepath)#获取文件的全路径
image_name=filepath
str1 = re.compile(strn+'''(.*?).csv''')
match_obj = re.findall(str1,image_name)
if match_obj:
print(image_name)
names.append(image_name)
# shutil.copy(image_name, targetDir) #复制到另一个路径
return names
getfilelist('hello')
这里根据自己的情况更改正则表达式:str1 = re.compile(strn+'''(.*?).csv''')
我本来这里的意思是找以‘python’开头,以‘.csv’结尾的文件,但是按照上面的情况,可能会将以下结果都匹配到:
['hello1.csv', 'hello3.csv', '你好hello2.csv', 'hellopython_1819你好.csv', '_hello_1517.csv123']
匹配到的结果是包含‘hello’,包含‘.csv’。
如果要找到以‘hello’开头,以‘.csv’结尾的文件,可以做这样的更改:str1 = re.compile('^'+strn+'''(.*?).csv$''') ,这个时候我们匹配到的结果就是:
['hello1.csv', 'hello3.csv', 'hello_1819你好.csv']
如果要找到以‘hello’开头,以‘.csv’结尾,并且后缀名的前面为数字的文件,可以做这样的更改:str1 = re.compile('^'+strn+'''(.*?)/d.csv$''') ,现在的匹配结果为:
['hello1.csv', 'hello3.csv']
我只列举了几种情况,这是正则表达式的内容,想要知道情况可以去搜索正则表达式哦
“当你的才华还撑不起你的野心的时候,你就应该静下心来学习”
以后这句话将会出现在我的每一篇博文中,用于提醒我自己,静下来好好学习。