对于python,我正在编写使用os.rename()
重命名文件的代码
到目前为止我所拥有的:
[os.rename(f, f.replace('New', '-'))
for f in os.listdir('.') if not f.startswith('.')]
我要做的是从C:\Users\MyName\Desktop\pythonVSC
到C:\Users\MyName\Desktop\pythonVSC\forTest
并将New
的所有情况改为-
在forTest
中,我有两个.txt
文件名New
和New_
我了解.replace
做什么,.listdir
做什么,.startwith
也做什么。你知道吗
我的问题是,如果我将for语句中的'.'
改为'./somePath'
,我会得到如下所示的错误
Exception has occurred: FileNotFoundError
[WinError 2] The system cannot find the file specified: 'New.txt' -> '-.txt'
File "C:\Users\MyName\Desktop\pythonVSC\rename.py", line 29, in <listcomp>
[os.rename(f, f.replace('New', '-')) for f in os.listdir('./forTest') if not f.startswith('.')]
File "C:\Users\MyName\Desktop\pythonVSC\rename.py", line 29, in <module>
[os.rename(f, f.replace('New', '-')) for f in os.listdir('./forTest') if not f.startswith('.')]
我试着用os.listdir('forTest')
,os.listdir('C:\Users\MyName\Desktop\pythonVSC\forTest')
和其他任何变体来替换os.listdir('.')
我在这里做什么?你知道吗
问题是您希望
os.listdir()
给您一个绝对路径列表,但实际上它只给您文件/目录的名称(basename)。 OTOHos.rename()
需要文件的路径。仅将文件名传递给os.rename()
的特殊情况只有在当前工作目录与试图重命名的文件相同时才有效。你知道吗您所引用的文件位于另一个目录中,但是
os.rename
不知道这一点。你知道吗最简单的解决方案是切换到另一个目录:
或者,更简单地说,传递完整的路径:
相关问题 更多 >
编程相关推荐