【问题标题】:Delete a range of files, skip a range, then repeat删除一系列文件,跳过一个范围,然后重复
【发布时间】:2017-10-17 20:13:39
【问题描述】:

我想为一个项目启动并运行一个代码。我对 Maya 的 python 很熟悉,但在 Windows 中处理文件时遇到了困难。基本上我想删除列表中的 64 个文件,跳过接下来的 64 个文件,然后重复。

到目前为止我得到的代码是:

     import os

     fileList = os.listdir("C:\Users\Tory\Desktop\Delete_Test")
     count = 1
     for F in fileList:
     if count < 64:
         os.remove(F)
         time.sleep(2)
         count = count + 1
     elif count < 128:
         count = count + 1
     else:
         count = 1

我得到的错误是“WindowsError: [Error 2] The system cannot find the file specified: 'HandDrawn_Access_IQ_Comp_14000.jpg'”

我不明白它是如何根据我告诉它的查找位置找不到它告诉我存在的文件的。我缺少某种格式吗?如果这很重要,我正在窗户上工作。

非常感谢!

【问题讨论】:

  • 如果你print(os.listdir("C:\Users\Tory\Desktop\Delete_Test")),你会看到什么?是绝对路径列表吗?
  • 嗨,当我打印,我得到:“ 'HandDrawn_Access_IQ_Comp_14000.jpg', 'HandDrawn_Access_IQ_Comp_14001.jpg', 'HandDrawn_Access_IQ_Comp_14002.jpg', 'HandDrawn_Access_IQ_Comp_14003.jpg', 'HandDrawn_Access_IQ_Comp_14004.jpg',“HandDrawn_Access_IQ_Comp_14005 .jpg'...."

标签: python windows file


【解决方案1】:

利用join

类似:

directory = "C:\\Users\\Tory\\Desktop\\Delete_Test"
for F in os.listdir(directory):
    file_path = os.path.join(directory, F)

【讨论】:

    【解决方案2】:

    这是一个简单的解决方案,可以批量删除目录中文件数量为n的64个文件

    import os
    import itertools
    
    folder = "C:\Users\Tory\Desktop\Delete_Test"
    files = os.listdir(folder)
    print("Total number of files in the folder: {0}".format(len(files)))
    
    skip = 64
    sets = len(files) / skip
    breaks = [(i*skip, i*skip+skip-1) for i in xrange(sets) if i % 2]
    
    files_to_delete = list(itertools.chain.from_iterable([files[start:stop] for start, stop in breaks]))
    print("No of files to be deleted: {0}".format(len(files_to_delete)))
    
    for filename in files_to_delete:
        filepath = os.path.join(folder, filename)
        print("Deleting file: {0}".format(filepath))
        os.remove(filepath)
    

    【讨论】:

    • 我尝试了这里列出的解决方案,它们不会抛出任何错误,但它们也不会删除文件。
    • @PolyGoop 我添加了用于调试的打印语句。我在 Unix 环境中对此进行了测试,问题可能与您在 Windows 中指定文件路径的方式有关。打印语句应该能够帮助您找到问题。
    猜你喜欢
    • 2013-09-14
    • 2012-11-27
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多