Python中的路径错误
我写了一个脚本来重命名一个文件
import os
path = "C:\\Users\\A\\Downloads\\Documents\\"
for x in os.listdir(path):
if x.startswith('i'):
os.rename(x,"Information brochure")
但是当这个Python文件和我指定的路径不在同一个文件夹时,就会出现找不到文件的错误
Traceback (most recent call last):
File "C:\Users\A\Desktop\script.py", line 5, in <module>
os.rename(x,"Information brochure")
FileNotFoundError: [WinError 2] The system cannot find the file specified:'ib.pdf'-> 'Information brochure'
不过如果我把Python文件复制到那个路径下,它就能正常工作了
import os
for x in os.listdir('.'):
if x.startswith('i'):
os.rename(x,"Information brochure")
这是什么问题呢?
2 个回答
0
这个x
变量里存的是文件的名字,但没有文件的完整路径。你可以这样做:
os.rename(path + "\\" + x, "Information brochure")
3
你的变量 x
现在只是相对于 path
的文件名。它是 os.listdir(path)
输出的内容。因此,你需要在 x
前面加上 path
,可以使用 os.path.join(path,x)
来做到这一点。
import os
path = "C:\\Users\\A\\Downloads\\Documents\\" #os.path.join for cross-platform-ness
for x in os.listdir(path):
if x.startswith('i'): # x, here is the filename. That's why it starts with i.
os.rename(os.path.join(path,x),os.path.join(path,"Information brochure"))