Python 代码打包文件名含中文乱码问题解决
在使用 Python 打包文件时,如果文件名包含中文,可能会出现乱码问题。这可能是因为在操作系统中使用的编码方式与 Python 默认编码方式不同导致的。
为了解决这个问题,可以在代码中指定编码方式。例如,可以使用以下代码将文件名编码为 UTF-8 并在输出时解码为 Latin-1:
import os
import subprocess
from alive_progress import alive_bar, config_handler
def pack_files(source_dir, output_dir):
# 检查源目录和输出目录是否存在
if not os.path.exists(source_dir) or not os.path.isdir(source_dir):
print(f'源目录{source_dir}不存在或不是一个目录')
return
if not os.path.exists(output_dir) or not os.path.isdir(output_dir):
print(f'输出目录{output_dir}不存在或不是一个目录')
return
# 计算文件总数
total_files = sum([len(files) for root, dirs, files in os.walk(source_dir)])
# 设置进度条样式
config_handler.set_global(length=40, spinner='classic', bar='classic', enrich_print=True)
with alive_bar(total_files, title='压缩进度') as bar:
for root, dirs, files in os.walk(source_dir):
for file in files:
# 获取需要压缩的文件路径
file_path = os.path.join(root, file)
# 获取文件名和文件后缀
file_name, file_ext = os.path.splitext(file)
# 拼接输出文件路径(去掉文件后缀)
output_file = os.path.join(output_dir, f'{file_name}.gz'.encode('utf-8').decode('latin1'))
if os.path.isdir(file_path):
# 处理文件夹,使用tar命令打包并压缩成tar.gz格式
tar_file = os.path.join(output_dir, f'{file_name}.tar.gz'.encode('utf-8').decode('latin1'))
subprocess.run(['tar', '-czf', tar_file, file_path])
else:
# 处理文件,使用pigz进行压缩
subprocess.run(['pigz', '-c', file_path],
stdout=open(output_file, 'wb'))
# 更新进度条
bar()
# 路径
source_dir = '/home/115/up'
output_dir = '/home/115/app'
pack_files(source_dir, output_dir)
在上面的代码中,我们使用 encode('utf-8').decode('latin1') 将文件名编码为 UTF-8 并在输出时解码为 Latin-1。这可以确保文件名在打包过程中不会出现乱码。
注意:
- 编码方式的具体选择取决于操作系统和 Python 环境的配置。
- 使用
encode('utf-8').decode('latin1')只是其中一种解决方案,具体情况还需要根据实际情况进行调整。
希望这篇文章能够帮助你解决 Python 打包文件名含中文乱码的问题。
原文地址: https://www.cveoy.top/t/topic/nDfE 著作权归作者所有。请勿转载和采集!