Akay
Akay

Reputation: 1

How to go through files in a directory and delete them depending on if the "time" column is less than local time

I am very new to python and right now I am trying to go through a directory of 8 "train" text files in which, for example one that says: Paris - London 19.10

What I want to do is create a code (probably some sort of for loop) to automatically go through and delete the files in which the time column is less than the local time. In this case, when the train has left. I want this to happen when i start my code. What I have manage to do is for this to happen only when I give an input to try to open the file, but I do not manage to make it happen without any input given from the user.

def read_from_file(textfile):
    try:
        infile = open(textfile + '.txt', 'r')
        infotrain = infile.readline().rstrip().split(' ')
        localtime = time.asctime(time.localtime(time.time()))
        localtime = localtime.split(' ')
        if infotrain[2] < localtime[3]:
            os.remove(textfile + '.txt')
            print('This train has left the station.')
            return None, None
    except:
        pass

(Be aware that this is not the whole function as it is very long and contains code that does not relate to my question) Does anyone have a solution?

Upvotes: 0

Views: 57

Answers (1)

ate50eggs
ate50eggs

Reputation: 454

os.listdir() gives you all of the the file names in a directory.

import os
file_names = os.listdir(".")
for fname in file_names:
    # do your time checking stuff here

Upvotes: 1

Related Questions