第1个回答 2019-01-17
import os
import re
reg=re.compile("指定内容正则表达式")
source="一个文件夹路径"
target="另一个文件夹路径"
for filename in os.listdir(source):
fullname=os.path.join(source,filename)
targetfile=os.path.join(target,filename)
if os.path.isfile(fullname) and os.path.splitext(filename)[1].lower()==".txt":
text=reg.search(open(fullname).read()).group(0)
open(targetfile,'w').write(text)
第2个回答 2019-01-17
import os,re
src_path = ''#src_path指源文件夹路径
des_path = ''#目标文件夹路径
pattern = re.compile(r'')#指定内容正则表达式
for root,paths,files in os.walk(src_path):
for file in files:#遍历源文件
with open(os.path.join(root, file), 'r') as f1:#打开源文件
with open(os.path.join(des_path, file), 'w+') as f2:#新建并打开新文件,文件名相同
f2.writer(pattern.match(f1.read()).group(0))#正则提取内容写入新文件,ps根据需要修改正则本回答被网友采纳
第3个回答 2019-01-17
#! /usr/bin/env python
# coding=utf-8
import os
import shutil
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def copy_and_rename(fpath_input, fpath_output):
for file in os.listdir(fpath_input):
oldname = os.path.join(fpath_input, file)
newname_1 = os.path.join(fpath_output,
os.path.splitext(file)[0] + "_1.jpg")
newname_2 = os.path.join(fpath_output,
os.path.splitext(file)[0] + "_2.jpg")
newname_3 = os.path.join(fpath_output,
os.path.splitext(file)[0] + "_3.jpg")
shutil.copyfile(oldname, newname_1)
shutil.copyfile(oldname, newname_2)
shutil.copyfile(oldname, newname_3)
if __name__ == '__main__':
print('start ...')
t1 = time.time() * 1000
#time.sleep(1) #1s
fpath_input = "D:/123/0708/"
fpath_output = "D:/345/0708/"
copy_and_rename(fpath_input, fpath_output)
t2 = time.time() * 1000
print('take time:' + str(t2 - t1) + 'ms')
print('end.')
第4个回答 2019-01-17
os.walk()了解下,这个可以实现遍历。
总正则把符合的抓出来,然后在写入另外一个文件夹即可。