【问题标题】:Python Delete Files in Directory from list in Text filePython从文本文件的列表中删除目录中的文件
【发布时间】:2018-10-11 04:38:11
【问题描述】:

我已经搜索了很多关于基于某些参数(例如所有 txt 文件)删除多个文件的答案。不幸的是,我还没有看到有人将较长的文件列表保存到 .txt(或 .csv)文件并希望使用该列表从工作目录中删除文件。

我将当前工作目录设置为 .txt 文件所在的位置(带有待删除文件列表的文本文件,每行一个)以及约 4000 个 .xlsx 文件。在 xlsx 文件中,我要删除大约 3000 个(在 .txt 文件中列出)。

这是我到目前为止所做的:

import os
path = "c:\\Users\\SFMe\\Desktop\\DeleteFolder"
os.chdir(path)
list = open('DeleteFiles.txt')
for f in list:
   os.remove(f)

这给了我错误:

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'Test1.xlsx\n'

我觉得我错过了一些简单的东西。任何帮助将不胜感激!

谢谢

【问题讨论】:

  • os.remove时需要提供完整路径

标签: python python-3.x


【解决方案1】:
  1. 从文本文件中读取的每一行中去除结尾 '\n'
  2. 通过将path与文件名连接起来制作绝对路径;
  3. 不要覆盖 Python 类型(即,在您的情况下为 list);
  4. 关闭文本文件或使用with open('DeleteFiles.txt') as flist

编辑:实际上,在查看您的代码时,由于os.chdir(path),可能不需要第二点。


import os
path = "c:\\Users\\SFMe\\Desktop\\DeleteFolder"
os.chdir(path)
flist = open('DeleteFiles.txt')
for f in flist:
    fname = f.rstrip() # or depending on situation: f.rstrip('\n')
    # or, if you get rid of os.chdir(path) above,
    # fname = os.path.join(path, f.rstrip())
    if os.path.isfile(fname): # this makes the code more robust
        os.remove(fname)

# also, don't forget to close the text file:
flist.close()

【讨论】:

  • 将我原来的 'os.remove(f)' 更改为 'os.remove(os.path.join(path, f.strip()))' 就成功了。并很好地提醒不要覆盖列表。非常感谢您的帮助!
【解决方案2】:

正如 Henry Yik 在评论中指出的那样,使用 os.remove 函数时需要传递完整路径。此外,open 函数只返回 file 对象。您需要从文件中读取行。并且不要忘记关闭文件。一个解决方案是:

import os
path = "c:\\Users\\SFMe\\Desktop\\DeleteFolder"
os.chdir(path)
# added the argument "r" to indicates only reading
list_file = open('DeleteFiles.txt', "r") 
# changing variable list to _list to do not shadow 
# the built-in function and type list
_list = list_file.read().splitlines() 
list_file.close()
for f in _list:
   os.remove(os.path.join(path,f))

进一步的改进是使用列表理解而不是循环和 with 块,它“自动”为我们关闭文件:

with open('DeleteFiles.txt', "r") as list_file:
    _list = list_file.read().splitlines()
    [os.remove(os.path.join(path,f)) for f in _list]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2011-05-15
    • 2023-04-03
    • 1970-01-01
    • 2014-04-27
    相关资源
    最近更新 更多