美好的一天!
我想问一下如何转换" .xlsx(excel)"的列表?从特定文件夹位置到" .zip"文件。 例: 路径:= C:\ My_Program \ zip_files
在我的zip_file文件夹中,我有多个" .xlsx"文件。 Test1.xlsx Test2.xlsx Test3.xlsx
我希望输出位于同一个文件夹中但是单独压缩。 输出: Test1.zip Test2.zip Test3.zip
希望somebady可以帮助我,我是python2或python3的新手。
答案 0 :(得分:1)
您有标准模块zipfile
来创建ZIP,glob.glob()
或os.listdir()
或os.walk()
来获取文件夹中的文件名。
编辑:应该有效(我在Linux上为我工作)
import os
import zipfile
folder = 'C:\\My_Program\\zip_files'
for filename in os.listdir(folder):
if filename.endswith('.xlsx'):
name_without_extension = filename[:-5] # string `.xlsx` has 5 chars
xlsx_path = os.path.join(folder, filename)
zip_path = os.path.join(folder, name_without_extension + '.zip')
zip_file = zipfile.ZipFile(zip_path, 'w')
# use `filename` (without folder name) as name inside archive
# and it will not create folders inside archive
zip_file.write(xlsx_path, filename)
zip_file.close()
编辑:与glob
import os
import glob
import zipfile
folder = 'C:\\My_Program\\zip_files'
for file_path in glob.glob(folder+'\\*.xlsx'):
filename = os.path.basename(file_path)
print(filename)
name_without_extension = filename[:-5]
print(name_without_extension)
xlsx_path = os.path.join(folder, filename)
zip_path = os.path.join(folder, name_without_extension + '.zip')
zip_file = zipfile.ZipFile(zip_path, 'w')
# use `filename` (without folder name) as name inside archive
# and it will not create folders inside archive
zip_file.write(xlsx_path, filename)
zip_file.close()