【问题标题】:delete all the files from a directory where filename starts with 'df' [duplicate]从文件名以“df”开头的目录中删除所有文件[重复]
【发布时间】:2019-12-08 20:24:08
【问题描述】:

我想从文件名以“df”开头的目录中删除所有文件。我曾经在下面的代码中做同样的事情,但我得到了下面的错误,说No such file or directory: 'df2.csv'although print 语句确实显示了 df2.csv

filelist = [ f for f in os.listdir("/a/b/") if f.startswith("df") ]
for f in filelist:
    print(f)
    os.remove(f)


df2.csv
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'df2.csv'

【问题讨论】:

标签: python python-3.x


【解决方案1】:

更新:

这是因为您只是将文件名及其扩展名添加到列表filelist

在这种特殊情况下,os.remove() 要求您将绝对路径传递给它,因为文件路径与脚本路径无关。

您需要将您的 filelist 列表理解更新为以下内容才能正常工作:

root = r'path to your directory'

filelist = [ os.path.join(root, f) for f in os.listdir(root) if f.startswith("df") ]

os.path.join(root, f) 将加入根路径和 filename.ext 创建一个绝对路径。

【讨论】:

  • os.remove 不需要绝对路径。只要正确,相对路径就可以工作。
猜你喜欢
  • 2012-01-02
  • 2022-01-11
  • 2015-10-08
  • 2014-12-12
  • 2014-03-29
  • 2020-01-06
  • 2023-03-20
  • 2017-09-19
相关资源
最近更新 更多