遍历目录中的文件

2024-04-20 00:53:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码应该得到最后修改过的文件并打印到屏幕上,而它一直在运行,直到一个新的文件被修改并打印到屏幕上,但是我总是得到一个类型错误。 TypeError:强制为Unicode:需要字符串或缓冲区,找到int。在

import os, sys, re, time
from datetime import date, timedelta, datetime
from time import localtime

files = os.listdir('dir_path')

files = [f for f in files if re.search('.csv', f, re.I)]
files.sort

d = datetime.now() - timedelta(days = 30)
d = d.timetuple()

oldfiles = 0
newfiles = 0
for file in files:
    filetimesecs = os.path.getmtime('dir_path' + file)
    filetime = localtime(filetimesecs)

if filetime < d:
    oldfiles += 1
if filetime > d:
    newfiles += open(files, 'r')
    for k in newfiles:
        sys.stderr.write(k)
    while True:
        time.sleep(2)
        print"new: %s" % newfiles

Tags: 文件pathinimportrefordatetimeif
2条回答

看来我们确实有一些打字错误,我会尽力把它弄清楚。在

oldfiles = 0
# if newfiles is an integer, I'm not sure that it will be
# as helpful to you, I think you'd really rather have a list
newfiles = list()
for file in files:
    filetimesecs = os.path.getmtime('C:/tmp/' + file)
    filetime = localtime(filetimesecs)
    if filetime < d:
        oldfiles += 1
    if filetime > d:
        newfiles.append(open('C:/tmp/' + file, 'r'))
        for k in newfiles:
            # read the entire file and write it to standard error
            sys.stderr.write(k.read())

# I believe you want the while out here, after everything is complete
# it would seem that you would want the newfiles loop within the first
# for loop
while True:
    time.sleep(2)
    print "new: %s" % newfiles

希望这有点价值。在

您的代码中有几处看起来很奇怪。例如:

files = [f for f in files if re.search('.csv', f, re.I)]

这真的是你想要的吗?除换行符外的任何字符都匹配。您可能需要对其进行转义以获得所需的行为,或者您可以使用f.endswith('.csv')进行测试。在

^{pr2}$

这不是函数调用。它应该是files.sort()

filetimesecs = os.path.getmtime('dir_path' + file)

最好使用os.path.join()连接目录路径和文件名。在

newfiles += open(files, 'r')

files变量是一个列表,不是字符串,对吗?你没有在这条线上出错吗?在

相关问题 更多 >