我想将文件从 {file1} 重命名为 {file2}。我读到os.rename(file1,file2)
在 python 中并且能够做到这一点。
只有当文件与python脚本放置在同一文件夹中时我才成功,所以我想问一下我们如何重命名其他文件夹的文件,即与放置python脚本的文件夹不同的文件夹。
最佳答案
只需使用完整路径,而不是相对路径:
oldFile = 'C:\\folder\\subfolder\\inFile.txt'
newFile = 'C:\\foo\\bar\\somewhere\\other\\outFile.txt'
os.rename(oldFile, newFile)
要获得双斜杠行为,您可以执行以下操作
import os
oldFile = r'C:\folder\subfolder\inFile.txt' # note the r character for raw string
os.path.normpath(oldFile)
输出
'C:\\folder\\subfolder\\inFile.txt'
关于python - 使用 python 重命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25342199/