在Python 2.7中重命名文件扩展名
问题描述:
我想将文本文件的扩展名重命名为zip,建议here。 正在编写的文件基于来自服务器的base64编码响应,在写入之前我正在对其进行解码。在Python 2.7中重命名文件扩展名
这是我的代码片段:
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
请协助。
答
file1 = "C:\Users\xyz\response.txt"
“\ r”是代表回车的单个字符。您可能没有名称中包含回车符的文件。如果您打算将它作为反斜杠后跟一个R,请使用原始字符串。
file1 = r"C:\Users\xyz\response.txt"
答
尝试改变这一行:
file1 = "C:\Users\xyz\response.txt"
这样:
file1 = "C:\\Users\\xyz\\response.txt"
或该:
file1 = r"C:\Users\xyz\response.txt"
'打印基地+ “的.zip”'' –
打印os.path.exists(file1)' –
您已收到在下面提供了正确的答案,但我会留下上述评论。当你遇到一个错误时,开始测试你的假设。就像打印语句一样简单就可以完成小脚本的工作。如果你运行这些打印语句,你会发现问题。 –