【问题标题】:Deleting files from a directory using a csv file in python使用python中的csv文件从目录中删除文件
【发布时间】:2020-06-28 02:47:54
【问题描述】:

我希望使用 .csv 文件从多个文件夹中删除文件。 csv 文件包含需要删除的文件名列表(例如:Box4, 60012-01)。数据如何存储在多个文件夹中,并且还有其他扩展名(例如:/tiles_20X_299/Box20/660491-3_mag20_xpos5980_ypos6279.jpg。有没有办法删除这些文件。非常感谢帮助。 这是我到目前为止所拥有的,但不确定我是否朝着正确的方向前进。 [要删除的 csv 文件示例][1]

fin = open('files_to_delete.csv', 'r')
fin.readline()
print(fin)
file_to_delete = set()
while True:
    line = fin.readline().strip()
    #print(line)
    if not line:
        break
    array = line.split(',')
    file_to_delete.add("Box" + array[0] + "/" + array[1])
fin.close()
print(file_to_delete)
#
for path in glob.glob('/home/sshah/Tiles/tiles_20X_299/*'):
    for f in file_to_delete:
        print(f)
        os.chdir(path)
        #print(path)
        if os.path.exists(f):
            print('delete')
            #os.remove(f)```


  [1]: https://i.stack.imgur.com/dFCxk.png

【问题讨论】:

  • 你的 csv 文件的格式是怎样的?请更新您的问题以包含前几行,包括标题。
  • 刚刚添加了csv文件@GordonAitchJay

标签: python file operating-system glob pathlib


【解决方案1】:

你肯定在朝着正确的方向前进。

假设您至少运行 3.5 版的 Python,您可以使用 glob.iglob() 递归迭代每个子目录中的每个文件。

我已经调整了您的代码,使其更具 Python 风格。

一些具体的变化:

  • file_to_delete set 重命名为files_to_delete,因为它包含多个文件并且应该是复数。

  • with 语句与文件对象上下文管理器 一起使用,以避免担心异常并显式调用.close()

  • 循环遍历fin 以获取每一行而不显式调用.readline()

  • 使用os.path.sep 而不是硬编码/

  • 删除了不必要的os.chdir(path)os.path.exists(f) 调用。

它的工作原理是遍历每个子目录中的每个文件(这为我们提供了完整的文件路径为 str),然后我们遍历 files_to_delete set 以检查每个 file_to_delete 是否是filepath。如果是,请删除该文件,然后 break 退出该循环以继续下一个文件路径。

如果您知道没有其他具有类似基础的文件名,您可以取消注释此行:files_to_delete.remove(file_to_delete)。例如,如果您有一个名为:

/tiles_20X_299/Box20/660491-3_mag20_xpos5980_ypos6279.jpg

但不是另一个叫:

/tiles_20X_299/Box20/660491-3_mag10_xpos2000_ypos4000.jpg

为安全起见,请将其注释掉。

import glob, os

files_to_delete = set()

with open('files_to_delete.csv', 'r') as fin:
    fin.readline() # Consume header
    for line in fin:
        line = line.strip()
        if line:
            files_to_delete.add('Box' + line.replace(',', os.path.sep)) # Assume none of the files contain a comma

print(files_to_delete)

for filepath in glob.iglob(r'/home/sshah/Tiles/tiles_20X_299/**/*', recursive=True):
    for file_to_delete in files_to_delete:
        if file_to_delete in filepath:
            print('Delete:', filepath)
            #os.remove(filepath)
            #files_to_delete.remove(file_to_delete)
            break

【讨论】:

  • 快速说明:glob.iglob 返回“一个迭代器,它产生与 glob() 相同的值,但实际上并没有同时存储它们。”。这可以节省内存。我不知道为什么这不是 Python 3 中 glob 的默认行为。
  • 这非常感谢您的帮助。 @GordonAitchJay
猜你喜欢
  • 2018-11-08
  • 2019-03-09
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 2011-01-01
  • 2023-04-03
  • 1970-01-01
  • 2015-12-26
相关资源
最近更新 更多