使用os.rename移动文件时出现问题



我有一段代码,我试图将文件夹中的所有文件移动到另一个文件夹。

import os
from os import listdir
from os.path import isfile, join
def run():
print("Do you want to convert 1 file (0) or do you want to convert all the files in a folder(1)")
oneortwo = input("")
if oneortwo == "0":
filepathonefile = input("what is the filepath of your file?")
filepathonefilewithoutfullpath = os.path.basename(filepathonefile)
newfolder = "C:/Users/EL127032/Documents/fileconvertion/files/" + filepathonefilewithoutfullpath
os.rename(filepathonefile,newfolder)
if oneortwo == "1" :
filepathdirectory = input("what is the filepath of your folder?")
filesindirectory = [f for f in listdir(filepathdirectory) if isfile(join(filepathdirectory, f))]
numberoffiles = len(filesindirectory)
handlingfilenumber = 0
while numberoffiles > handlingfilenumber:
currenthandlingfile = filesindirectory[handlingfilenumber]
oldpathcurrenthandling = filepathdirectory + "/" + currenthandlingfile
futurepathcurrenhandlingfile = "C:/Users/EL127032/Documents/fileconvertion/files/" + currenthandlingfile
os.rename(oldpathcurrenthandling, futurepathcurrenhandlingfile)

但当我运行这个时,它会os.rename(旧路径当前处理,未来路径当前处理文件(FileNotFoundError:[WinError 2]系统找不到文件:"C:\Users\EL127032\Documents\Eligant-kopie\Klas 1\Stermodules\Basisbiologie/lopen(1(.odt'->"C:/Users/EL127032/Documents/fileconversion/files/lopen(1(.odt'

有人能帮帮我吗。

您正试图移动同一个文件两次。

错误在这个部分:

numberoffiles = len(filesindirectory)
handlingfilenumber = 0
while numberoffiles > handlingfilenumber:
currenthandlingfile = filesindirectory[handlingfilenumber]
oldpathcurrenthandling = filepathdirectory + "/" + currenthandlingfile
futurepathcurrenhandlingfile = "C:/Users/EL127032/Documents/fileconvertion/files/" + currenthandlingfile
os.rename(oldpathcurrenthandling, futurepathcurrenhandlingfile)

第一次循环时,handlingfilenumber将为0,因此您将从filesindirectory列表中移动第0个文件
然后再次循环,handlingfilenumber仍然为0,因此您尝试再次移动它,但它已不在那里(您在第一个转弯时已经移动了它(。

您忘记递增handlingfilenumber。在os.rename后面的一行加上handlingfilenumber += 1,就可以了。

while循环比简单的for循环更容易出错,我建议您在适当的时候使用for循环
在这里,您需要移动每个文件,因此for循环就足够了:

for filename in filesindirectory:
oldpathcurrenthandling = filepathdirectory + "/" + currenthandlingfile
futurepathcurrenhandlingfile = "C:/Users/EL127032/Documents/fileconvertion/files/" + currenthandlingfile
os.rename(oldpathcurrenthandling, futurepathcurrenhandlingfile)

无需使用len,初始化计数器,递增,获得第n个元素。。。行数更少。

其他三件事:

  • 您可以自己找到问题的原因,使用调试,有很多在线资源可以解释如何做到这一点。只需打印要复制的文件的名称(oldpathcurrenthandling(,您就会看到两次,并注意到导致os错误的问题
  • 您的变量名不太可读。考虑遵循关于变量名(PEP 8(和标准术语的标准样式指南,例如filepathonefilewithoutfullpath变为filenameoldpathcurrenthandling变为source_file_path(遵循源/目的地约定(
  • 当您出现错误时,请包括Python提供的stacktrace。它会直接指向第二种os.rename情况,第一种情况(当您只复制一个文件时(不会导致问题。它也有助于找到一个最小可复制的例子

最新更新