简体   繁体   English

根据文件名中的日期删除文件

[英]Deleting files based on day within filename

I have a directory with files like: data_Mon_15-8-22.csv , data_Tue_16-8-22.csv , data_Mon_22-8-22.csv etc and I am trying to delete all but the Monday files. I have a directory with files like: data_Mon_15-8-22.csv , data_Tue_16-8-22.csv , data_Mon_22-8-22.csv etc and I am trying to delete all but the Monday files. However, my script doesn't seem to differentiate between the filenames and just deletes everything despite me stating it.但是,我的脚本似乎没有区分文件名,尽管我声明了它,但它只是删除了所有内容。 Where did I go wrong?我在哪里 go 错了? Any help would be much appreciated!任何帮助将非常感激!

My Code:我的代码:

def file_delete():
    directory = pathlib.Path('/Path/To/Data')
    for file in directory.glob('data_*.csv'):
        if file != 'data_Mon_*.csv':
            os.remove(file)]

if all Monday files start with "data_Mon_" then you might use str.startswith:如果所有星期一文件都以“data_Mon_”开头,那么您可以使用 str.startswith:

def file_delete():
    directory = pathlib.Path('/Path/To/Data')
    for file in directory.glob('data_*.csv'):
        if not file.name.startswith('data_Mon_'):
            os.remove(file)
if file != 'data_Mon_*.csv'

There's two problems here:这里有两个问题:

file is compared against the string 'data_Mon_*.csv' . file与字符串'data_Mon_*.csv'进行比较。 Since file isn't a string, these two objects will never be equal.由于file不是字符串,因此这两个对象永远不会相等。 So the if condition will always be true.所以if条件永远为真。 To fix this, you need to get the file's name, rather than using the file object directly.要解决此问题,您需要获取文件名,而不是直接使用文件 object。

Even if you fix this, the string 'data_Mon_*.csv' is literal.即使您解决了这个问题,字符串'data_Mon_*.csv'也是文字。 In other words, the * is a * .换句话说, *是一个* Unlike directory.glob('data_*.csv') , this will only match a * rather than match "anything" as in a glob expression.directory.glob('data_*.csv')不同,这只会匹配*而不是匹配 glob 表达式中的“任何内容”。 In order to fix this, you need to use a regular expression to match against your file name.为了解决这个问题,您需要使用正则表达式来匹配您的文件名。

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

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