首页 > 解决方案 > 在 Python 中用汉字重命名文件

问题描述

我正在尝试重命名一些包含中文字符的文件。但是,以下内容不起作用:

import os

for filename in os.listdir(r"C:\Users\mas\Desktop\"):
    if filename.startswith("你好"):
        os.rename(filename, filename[7:])

它给出了错误“系统找不到指定的文件:'你好Hello.txt”

我需要在这里更改一些设置吗?

标签: pythonwindowsunicodefilesystems

解决方案


根据错误消息,似乎找不到文件

我遇到了类似的问题,我首先通过更改当前工作目录来解决它

在你的情况下

# Change working directory first
os.chdir("C:\Users\mas\Desktop")

# then do the loop
for filename in os.listdir(r"C:\Users\mas\Desktop\"):
    ...

推荐阅读