Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How would you scan a dir for a text file and read the text file by date modified, print it to screen having the script scan the directory every 5 seconds for a newer file creadted and prints it. Is it possible that you can help me i'm stuck and i need this real bad and i've already got the scan dir for file and print but it does not print the files by date modidfied.

import os,sys
os.chdir(raw_input('dir_path: ') )    
contents=os.listdir('.') #contents of the current directory
files =[]
directory=[]
Time = time.ctime(os.path.getmtime(contents))
for i in contents:
    if os.path.isfile(i) == True :
       files.append(i)
    elif os.path.isdir(i) == True :
       directory.append(i)
    #printing contents
choice = ""       
for j in files:
    while choice != "quit":
            choice = raw_input("Dou you want to print file  %s (y/n): "%j)
            if choice == 'y':
               print "**************************"
               print "Printing Files %s" %j
               print "**************************"
               fileobj = open(j,'r')
               contents = fileobj.readlines()
               for k in contents:
                     sys.stderr.write(k)
               else:
                    pass

what i wanted is instead of my code asking if it wants to print i need it to print the files if modified by the current time meaning if it read a file that was just placed in the directory and a new one comes in it will read the new file without prompting me. the error it's giving me is coercing to unicode: need string or buffer, list found.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

Repeating actions on a timer

You can repeat an action every five seconds by combining an infinite loop with the time.sleep() function, like so:

import time
while True:
    time.sleep(5)         # wait five seconds
    print (time.time())   # print the time

Remember to have some kind of break condition in here if you need it, otherwise the loop will run forever.

"TypeError: coercing to Unicode: need string or buffer, list found"

Your problem is in the line

Time = time.ctime(os.path.getmtime(contents))

You have provided a list of filenames. The os.path.getmtime function expects one filename at a time. The error message is telling you that it has no idea how to convert a list of filenames into a filename.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...