Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 文件修改和操作_Python_File_Time_Timer - Fatal编程技术网

Python 文件修改和操作

Python 文件修改和操作,python,file,time,timer,Python,File,Time,Timer,如何扫描目录中的文本文件,并按修改的日期读取文本文件,将其打印到屏幕上,让脚本每5秒扫描一次目录中的更新文件,并将其打印出来。 你能帮我吗?我被卡住了,我非常需要这个,我已经有了文件和打印的扫描目录,但它不会按修改的日期打印文件 import os,sys os.chdir(raw_input('dir_path: ') ) contents=os.listdir('.') #contents of the current directory files =[] directory=[]

如何扫描目录中的文本文件,并按修改的日期读取文本文件,将其打印到屏幕上,让脚本每5秒扫描一次目录中的更新文件,并将其打印出来。 你能帮我吗?我被卡住了,我非常需要这个,我已经有了文件和打印的扫描目录,但它不会按修改的日期打印文件

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:需要字符串或缓冲区,找到列表。

在计时器上重复操作

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

import time
while True:
    time.sleep(5)         # wait five seconds
    print (time.time())   # print the time
如果需要,记得在这里设置某种
中断
条件,否则循环将永远运行

“类型错误:强制使用Unicode:需要字符串或缓冲区,找到列表”

你的问题就在眼前

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

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

您的问题不清楚。“按修改日期读取文本文件”是什么意思?您的意思是要按修改时间的顺序打印所有文件吗?还是只想打印自上次查看该文件以来已更改的文件?是否使用linux?如果是这样,有一种更好的方法来监视目录中的文件系统事件:。和也有类似的解决方案。请不要发布。这是非常不礼貌的。我只想打印上次更改的文件。我的意思是按修改后的时间逐个打印目录中的文件?
内容
,由
os.listdir()
返回,是一系列文件名。思考如何使用
for
循环逐个元素遍历序列元素。