【问题标题】:I get the error :[WinError 2] The system cannot find the file specified:我收到错误:[WinError 2] 系统找不到指定的文件:
【发布时间】:2021-08-18 13:05:11
【问题描述】:

此代码将所有 pdf 文件移动到一个名为 pdf 的文件夹中。它移动第一个文件然后得到移动文件的错误:[WinError 2] 系统找不到指定的文件:'C:\Users\farbod\Desktop\Print Form.pdf' -> 'C:/Users/farbod/Desktop/pdf/Print Form.pdf' 注意:我也使用了shutil而不是pathlib。同样的错误



import os
from pathlib import Path




path ="C:/Users/farbod/Desktop"
pdf_folder_path = "C:/Users/farbod/Desktop/pdf"
files=[]

os.chdir(path)
files = os.listdir(path)
for file in files:
    file_path= path + '/' + file
    file_name,file_ext= os.path.splitext(file_path)
    if file_ext==".pdf":
        os.rename(file_path,pdf_folder_path+'/'+file)
        Path(file_path,).rename(pdf_folder_path+'/'+file)
    else:
        continue

【问题讨论】:

  • 文件在pdf子目录下吗?如果是这样,那就是问题所在:您只是在父目录上调用os.listdir()。看看os.walk 之类的东西,以便能够递归地下降到任何和所有子目录。

标签: python error-handling


【解决方案1】:

已修复且可正常工作的代码。谢谢 Ghost Ops 先生

import os


pdf_folder_path = "/pdf/"

os.chdir("C:/Users/farbod/Desktop")
files = os.listdir()
for file in files:
    file_path= f"{file}"
    file_name,file_ext= os.path.splitext(file_path)
    if file_ext==".pdf":
        #your if statement didnt work because i had a folder called pdf.
        os.rename(file_path,"C:/Users/farbod/Desktop/pdf"+"/"+file)
        
        



【讨论】:

    【解决方案2】:

    我认为这是您要查找的代码

    如果有错误请告诉我

    import os
    # from pathlib import Path
    
    os.chdir("C:/Users/farbod/Desktop")
    files = os.listdir()
    for file in files:
        if file.split('.')[-1] == "pdf":
            os.rename(file, f"/pdf/{file}")
            # Path(file).rename(f"/pdf/{file}")
            # I can't understand why you have to move a file using 2 same functioning lines
            # (or guess what, i don't know to use pathlib. os.rename is enough to move a file)
    

    【讨论】:

    • 非常感谢。这真的很有帮助。我在您的代码中进行了调试,现在它可以正常工作了。
    • 接受答案并关闭问题,如果它完成了......或者至少标记正确的答案(你的)它会对其他人有所帮助
    猜你喜欢
    • 2021-07-14
    • 1970-01-01
    • 2017-08-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多