Python - zipfiles的问题[关闭]
Posted
技术标签:
【中文标题】Python - zipfiles的问题[关闭]【英文标题】:Python - Problems with zipfiles [closed] 【发布时间】:2020-11-11 09:50:26 【问题描述】:包含 20 个文本文件的我的 zip 文件(文件夹)保存在本地。我有那个目录。 我想做什么:
-
我想上压缩文件夹,循环搜索,以获得正确的文本文件(例如“testcase1”),应该对其进行编辑。
打开此文本文件并添加新行,例如“hello world” -> 保存并关闭
接下来我想再次压缩这个文件夹并将其保存在本地的一个特殊目录中
返回新压缩文件(文件夹)的路径
【问题讨论】:
你的问题有点混乱。如果您在打开、读取和写入文件时遇到问题,请分享您尝试过的代码。如果 Zip 相关功能正常工作,请从您的问题中删除这些功能。 【参考方案1】:这对我有用:
import zipfile
def update_log(self, input_dir, output_dir):
'''
function to update the log files
'''
with ZipFile(input_dir, 'r') as zip:
# printing all the contents of the zip file
zip.printdir()
# extracting all the files
self.logger.info("Extracting all the files now...")
os.chdir(output_dir)
zip.extractall()
print('Done!')
#for loop, opening file, edit and close
for key in testcase_dict:
log_file = open('.txt'.format(key), 'a')
log_file.write('hello world')
log_file.close()
# calling function to get all file paths in the directory
file_paths = self.get_all_file_paths()
# printing the list of all files to be zipped
for file_name in file_paths:
print(file_name)
# writing files to a zipfile
with ZipFile('log-test.zip', 'w') as zip:
# writing each file one by one
for file in file_paths:
zip.write(file)
print("All files zipped successfully")
return None
def get_all_file_paths(self):
# initializing empty file paths list
file_paths = []
# crawling through directory and subdirectories
for root, directories, files in os.walk("home/test"):
for filename in files:
# join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath)
# returning all file paths
self.logger.info(file_paths)
return file_paths
【讨论】:
以上是关于Python - zipfiles的问题[关闭]的主要内容,如果未能解决你的问题,请参考以下文章