0

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?

Akay
  • 1
  • 2
  • You may wish to add a infile.close() statement when you are finished with the file handler.. – Mark N Jul 14 '15 at 18:03
  • I'm voting to close as too broad right now because it's hard for me to tell what your actual question is as written. You are asking, I think, how to get an algorithm to work without requiring user input, but nowhere in your posted code do you ask for any. You should post a _representative_ example of your code and exactly how your files are formatted. – Two-Bit Alchemist Jul 14 '15 at 18:05
  • This question seems to be a duplicate/similar to http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python?rq= – Mark N Jul 14 '15 at 18:07
  • @Two-BitAlchemist the code I posted does the same thing I want my program to do, but I want it to do it without a try function and with a for loop instead, in that way the program will automatically go through the textfiles without me having to give any input. – Akay Jul 14 '15 at 18:24
  • Re: getting rid of try, just do it. You are catching _every_ exception which is a bad idea anyway, and you're not even doing anything if you catch them. Re: for loop you seem to have an answer for that below. – Two-Bit Alchemist Jul 14 '15 at 18:28

1 Answers1

1

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
ate50eggs
  • 444
  • 3
  • 14