简体   繁体   English

使用 python 删除某些文件

[英]Deleting certain files using python

I have a py script that processes files with extension '.hgx'.Example: test.hgx ( there are many such files with extension hgx)我有一个 py 脚本,它处理扩展名为“.hgx”的文件。示例:test.hgx(有很多这样的文件扩展名为 hgx)

The script processes the test.hgx and creates a new test_bac.hgx and on re-run it creates test_bac_bac.hgx.该脚本处理 test.hgx 并创建一个新的 test_bac.hgx 并在重新运行时创建 test_bac_bac.hgx。 So everytime running the script creates a file with '_bac'.所以每次运行脚本都会创建一个带有“_bac”的文件。

Is there some solution that I can use in my script that can delete all the existing '_bac' and '_bac_bac...' files before start of the actual code.是否有一些解决方案可以在我的脚本中使用,可以在实际代码开始之前删除所有现有的 '_bac' 和 '_bac_bac...'文件。

I am already using glob.glob function我已经在使用 glob.glob function

for hgx in glob.glob("*.hgx"):  

Can I use this function to delete these files 'X_bac.hgx' and other _bac_bac..hgx files?我可以使用这个 function 删除这些文件 'X_bac.hgx' 和其他 _bac_bac..hgx 文件吗?

Any help/idea would be appreciated.任何帮助/想法将不胜感激。

Thanks谢谢

import os
import glob
for hgx in glob.glob("*_bac.hgx"):
  os.remove(hgx)

A very similar solution would be一个非常相似的解决方案是

import os
import glob
map(os.remove, glob.glob("*_back.hgx"))

But besides having a slightly more compact expression, you save one variable name in the current namespace.但是除了有一个稍微紧凑的表达式之外,您还可以在当前命名空间中保存一个变量名。

glob.glob("*_bac.hgx") will get you the files. glob.glob("*_bac.hgx")将为您提供文件。 You can then use the os.remove function to delete the file in your loop.然后,您可以使用os.remove function 删除循环中的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM