我正在尝试使用os.rename()
def unzip(date,day,zip_file):
dest_dir = 'C:/Users/mbelahce040119/PycharmProjects/kpi/flats'
with ZipFile(zip_file) as zipObj:
files_sat = list()
for zip_info in zipObj.infolist():
if zip_info.filename[-1] == '/':
continue
if zip_info.filename.startswith(date,42,50):
files_sat.append(zip_info.filename)
zip_info.filename = os.path.basename(max(files_sat))
print(max(files_sat))
zipObj.extract(max(files_sat), dest_dir)
old_file = os.path.join(dest_dir,max(files_sat))
new_file = os.path.join(dest_dir,date+'_D+'+day+'.csv')
os.rename(old_file,new_file)
但是,我不知道如何将新文件名传递给extract函数,也不知道它应该在提取之前还是之后。到目前为止,由于我在前面的行中更改了名称,因此没有提取。
答案 0 :(得分:1)
以下是使用pathlib
的替代版本:
from pathlib import Path
from zipfile import ZipFile
def unzip(date, day, zip_file):
dest_dir = Path('C:/Users/mbelahce040119/PycharmProjects/kpi/flats')
with ZipFile(zip_file) as zipObj:
filelist = []
for file in zipObj.infolist():
if file.filename.startswith(date, 42, 50) and not file.is_dir():
filelist.append(Path(file.filename))
final_file = sorted(filelist).pop()
zipObj.extract(final_file, dest_dir)
final_file = dest_dir/final_file.name
final_file.rename(dest_dir/f'{date}_D{day}.csv')
由于我是根据您的初始代码编写的,因此未经测试。
答案 1 :(得分:0)
我知道了。问题是我已经将文件名更改为基本名称,所以我不得不使用基本名称进行重命名。
def unzip(date,day,zip_file):
dest_dir = 'C:/Users/mbelahce040119/PycharmProjects/kpi/flats'
with ZipFile(zip_file) as zipObj:
files_sat = list()
for zip_info in zipObj.infolist():
if zip_info.filename[-1] == '/':
continue
if zip_info.filename.startswith(date,42,50):
files_sat.append(zip_info.filename)
zip_info.filename = os.path.basename(max(files_sat))
print(max(files_sat))
final_file = max(files_sat)
zipObj.extract(final_file, dest_dir)
old_file = os.path.join(dest_dir,os.path.basename(final_file))
new_file = os.path.join(dest_dir,date+'_D+'+day+'.csv')
os.rename(old_file,new_file)