文件修改和处理 [英] file modifiaction and manipulation

查看:46
本文介绍了文件修改和处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何扫描目录中的文本文件并按修改后的日期读取文本文件,将其打印到屏幕上,让脚本每5秒扫描一次目录,以读取新文件并打印. 是否有可能您可以帮助我,我被卡住了,我需要这个真正的好工具,并且我已经有了文件和打印的扫描目录,但它没有按修改的日期打印文件.

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

我想要的是代替我的代码询问是否要打印的代码,如果需要在当前时间进行修改,我需要它打印文件,这意味着它是否读取了刚刚放在目录中的文件,并且有一个新文件进入其中会在不提示我的情况下读取新文件. 它给我的错误是强制使用unicode:需要字符串或缓冲区,找到了列表.

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.

推荐答案

在计时器上重复操作

通过将无限循环与time.sleep()函数结合使用,您可以每五秒钟重复一次操作,如下所示:

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

如果需要,请记住在其中具有某种break条件,否则循环将永远运行.

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

"TypeError:强制转换为Unicode:需要字符串或缓冲区,找到列表"

您的问题就在这里

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

您提供了文件名的列表. os.path.getmtime函数期望一次一个文件名.错误消息告诉您,它不知道如何将文件名列表转换为文件名.

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.

这篇关于文件修改和处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆