Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

python - file modifiaction and manipulation

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...