【问题标题】:Renaming file extension in Python 2.7在 Python 2.7 中重命名文件扩展名
【发布时间】:2016-10-14 05:27:45
【问题描述】:

我正在尝试按照here 的建议将文本文件的扩展名重命名为 zip。 该文件是根据来自服务器的 base64 编码响应写入的,我在写入之前对其进行解码。

这是我的代码 sn-p:

f = open("response.txt","wb")
f.write(json.loads(response.text)['Binary'].decode('base64'))
f.close()
file1 = "C:\Users\xyz\response.txt"
base = os.path.splitext(file1)[0]
os.rename(file1, base + ".zip")

即使文件位于我的代码中指定的绝对路径中,我也会收到以下错误:

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

请帮忙。

【问题讨论】:

  • print base + ".zip"
  • print os.path.exists(file1)
  • 您在下面收到了正确的答案,但我会留下上面的 cmets。当您遇到错误时,请开始测试您的假设。像打印语句这样简单的东西可以为小脚本完成这项工作。如果您运行这些打印语句,您就会发现问题。

标签: python rename


【解决方案1】:

尝试更改此行:

file1 = "C:\Users\xyz\response.txt"

到这里:

file1 = "C:\\Users\\xyz\\response.txt"

或者这个:

file1 = r"C:\Users\xyz\response.txt"

【讨论】:

    【解决方案2】:
    file1 = "C:\Users\xyz\response.txt"
    

    "\r" 是表示回车的单个字符。您可能没有名称中包含回车的文件。如果您打算将其作为反斜杠后跟 R,请使用原始字符串。

    file1 = r"C:\Users\xyz\response.txt"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 2018-01-11
      • 2017-07-05
      相关资源
      最近更新 更多