【问题标题】:Why my Python program can't run correctly? It can run but don't get the result I want to为什么我的 Python 程序无法正常运行?它可以运行但没有得到我想要的结果
【发布时间】:2015-04-21 09:15:02
【问题描述】:

程序的作用是将两个文件夹压缩,然后保存到一个文件夹中。该程序可以运行,但我收到一条错误消息,如下所示:

C:\Python34\python.exe D:/Python/backup_ver1.py
'zip' �����ڲ����ⲿ���Ҳ���ǿ����еij���
�����������

Failed backup

是的,就像你看到的那样。我无法从中获得更多信息。

代码如下:

import os
import time
source = ['E:\\source1','E:\\source2']
target_dir = 'E:\\target'
target = target_dir + os.sep + time.strftime("%Y%m%d%H%M%S") +'.zip'
zip_command = 'zip -qr {0} {1}'.format(target,' '.join(source))

if os.system(zip_command) == 0:
    print("Successful bakup to",target)
else:
    print("Failed backup")

我的电脑中有“source1”、“source2”和“target”。

【问题讨论】:

  • 你为什么使用系统调用而不是使用内置的 zip api? docs.python.org/3/library/zipfile.html
  • 打印出zip_command 并在shell 中运行它。有用吗?
  • 这段代码看起来很眼熟——今天你班上还有多少人在问这个问题?
  • 这是 Windows 吗?您使用的是什么 zip 实用程序?
  • 您应该使用 op.path 来操作(例如加入)路径。输出看起来像一些控制代码或混乱的控制台。你是从哪里运行这个程序的(IDE、控制台、IDLE、...)?

标签: python python-3.x


【解决方案1】:

我在我的系统上使用 7zip,所以我的语法和你的有点不同。 试试这个:

import os
import time
source = ['d:\\source1','d:\\source2']
target_dir = 'd:\\target'
target = target_dir + os.sep + time.strftime("%Y%m%d%H%M%S") +'.zip'
zip_command = '"C:\\Program Files\\7-Zip\\7z.exe" a {0} {1}'.format(target,' '.join(source))
if os.system(zip_command) == 0:
    print("Successful bakup to",target)
else:
    print("Failed backup")

【讨论】:

  • 非常感谢。你太友好了。
猜你喜欢
  • 2015-07-12
  • 2011-12-04
  • 2020-11-02
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多