迭代目录中的文件

时间:2012-03-07 17:40:29

标签: python file-io time

我的代码应该获取最后修改过的文件,并在它继续运行时打印到屏幕,直到新文件被修改并将其打印到屏幕,但我一直得到一个typeError。 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

2 个答案:

答案 0 :(得分:1)

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

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

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

files.sort

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

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

最好使用os.path.join()加入目录路径和文件名。

newfiles += open(files, 'r')

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

答案 1 :(得分:1)

似乎我们确实有一些类型错误,我会尽力清除这一点。

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

希望这有一些价值。