Python从文本文件列表中删除目录中的文件

标签 python python-3.x

我搜索了很多关于根据特定参数(例如所有 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'

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

谢谢

最佳答案

  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()

关于Python从文本文件列表中删除目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52752322/

相关文章:

python - 在 Vimscript 中,是否可以访问语法荧光笔已知的信息?

python - Python 中 'x = y = z' 赋值的语义

python - Django ALLOWED_HOSTS 与 CORS(django-cors-headers)

python - 将Python Kivy程序转换为C代码

javascript - 如何从 sqlalchemy jsonify 对象?

python - 如何在 python 上生成安全 session_id ?

python - 如何让我的 discord 机器人在加入语音 channel 时立即播放音频文件,例如 airhorn solutions 机器人?

python - 在 PyQt5 中通过对象 #id 设置样式

c - Linux Ubuntu 如何获取远程主机名

python-3.x - 属性错误: 'list' object has no attribute 'create_png'