【问题标题】:How do I move file types not a specific file in PyCharm?如何在 PyCharm 中移动文件类型而不是特定文件?
【发布时间】:2020-04-22 14:05:14
【问题描述】:

我正在尝试制作一个程序来组织我每次下载内容时的下载文件夹,但如果我使用此代码:

import shutil

shutil.move("/Users/plapl/downloads/.zip", "/Users/plapl/Desktop/Shortcuts/winrar files")
shutil.move("/Users/plapl/downloads/.png", "/Users/plapl/Desktop/Shortcuts/images")

它搜索名为 .zip 和 .png 的文件名,但我希望它搜索所有该类型的文件。谁能告诉我该怎么做?

【问题讨论】:

    标签: python file-organization


    【解决方案1】:

    您想遍历目录中的文件。这是来自source的示例

    import shutil
    import os
    source = os.listdir("/Users/plapl/downloads/")
    destination = "/Users/plapl/Desktop/Shortcuts/winrar files"
    for files in source:
        if files.endswith(".zip"):
            shutil.move(files,destination)
    

    【讨论】:

      【解决方案2】:

      我以此为基础做了一些东西,但它说未解决的参考“文件”

      import shutil
      
      import os
      
      
      source = os.listdir("/Users/plapl/Downloads/")
      
      destination1 = "/Users/plapl/desktop/Shortcuts/images"
      
      destination2 = "/Users/plapl/Shortcuts/winrar files"
      
      destination3 = "/Users/plapl/torrents"
      
      for files in source:
          if file.endswith(".png"):
              shutil.move(files, destination1)
      
          if file.endswith(".zip"):
              shutil.move(files, destination2)
      
          if file.endswith(".torrent"):
              shutil.move(files, destination3)
      
      

      【讨论】:

        【解决方案3】:

        它抱怨变量名file 没有定义。

        你应该使用files,因为那是你的迭代变量名。

        【讨论】:

        • 谢谢,这有帮助,但我遇到了另一个错误,它选择了一个具有这种结尾类型的随机文件,FileNotFoundError: [Errno 2] No such file or directory: '(file's name).torrent '
        • 问题是你只提供了移动操作的文件名,它会在你执行代码的当前目录中查找。因此,您应该将文件的整个路径传递给移动操作。 dir_name = "/Users/plapl/Downloads/" #<the path you used to get the source> for files in source: if files.endswith(".pdf"): shutil.move(os.path.join(dir_name, files), destination3)
        猜你喜欢
        • 2019-09-13
        • 1970-01-01
        • 2014-06-26
        • 1970-01-01
        • 2014-02-11
        • 2021-01-24
        • 2015-07-10
        • 2015-02-20
        • 1970-01-01
        相关资源
        最近更新 更多