仅需重新使用Python并尝试构建一个与文件名匹配的脚本,对其进行重命名,压缩,然后最终从它们构建一个控制文件(我尚未编写)。它适用于放置在目录中的文件,但最后出现错误:FileNotFoundError:[WinError 2]系统找不到指定的文件:'A20190331.txt'->'B20190530.txt'。重命名后是否会在开始时重新运行我的txt_files循环?此时代码可能不是最佳的。
import os
import zipfile
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile.ZIP_STORED
path = 'mypath'
txt_files = []
for root, dirs, files in os.walk(path):
for file in files:
txt_files.append(file)
def create_zip(data_dt):
for files in txt_files:
if '.py' in files:
continue
elif 'A' in files:
file_name = 'A' + data_dt + '.txt'
name_full_path = path +'\\'+ file_name
os.rename(files, file_name)
zf = zipfile.ZipFile('A' + data_dt+ '.zip', mode='w')
zf.write(name_full_path, file_name, compress_type=compression)
zf.close()
elif 'B' or 'C' in files:
file_name = 'B' + data_dt + '.txt'
name_full_path = path +'\\'+ file_name
os.rename(files, file_name)
zf = zipfile.ZipFile('B' + data_dt +'.zip', mode='w')
zf.write(name_full_path, file_name, compress_type=compression)
zf.close()
else:
break
create_zip('20190530')
答案 0 :(得分:1)
克里斯托弗。
我立即看到您的问题:
txt_files = []
for root, dirs, files in os.walk(path):
for file in files:
txt_files.append(file)
我相信您想继续前进:
for root, dirs, files in os.walk(path):
for file in files:
txt_files.append(os.path.join(os.path.get_cwd(), file))
让os.path为您处理路径-它可以跨平台移植并且不易出错。
hth
答案 1 :(得分:0)
我做了一些修改,请您尝试一下,但是用您的方式,代码将覆盖文件。 因此,请尝试使用此脚本,并告诉我要覆盖还是重命名并压缩
def create_zipe(data_dt):
for files in txt_files:
if '.py' in files:
continue
elif 'ASS' in files:
file_name = 'A' + data_dt + '.txt'
name_full_path = path +'/'+ file_name
os.rename(files, file_name)
zf = zipfile.ZipFile('A' + data_dt+ '.zip', mode='w')
zf.write(name_full_path, file_name, compress_type=compression)
zf.close()
elif 'C' in files or 'B' in files:
file_name = 'B' + data_dt + '.txt'
print(file_name)
name_full_path = path +'/'+ file_name
print(name_full_path)
os.rename(files, file_name)
zf = zipfile.ZipFile('B' + data_dt+ '.zip', mode='w')
zf.write(name_full_path, file_name, compress_type=compression)
zf.close()