2012-10-10 45 views
1

我在目录中有一些txt文件,我需要从所有目录中获取最后15行。我怎么能用python来做到这一点?使用python获取目录中所有.txt文件的行

我选择了这个代码:

from os import listdir 
from os.path import isfile, join 

dir_path= './' 
files = [ f for f in listdir(dir_path) if isfile(join(dir_path,f)) ] 
out = [] 
for file in files: 
    filedata = open(join(dir_path, file), "r").readlines()[-15:] 
    out.append(filedata) 
f = open(r'./fin.txt','w') 
f.writelines(out) 
f.close() 

,但我得到的错误“类型错误:writelines()参数必须是串序列”。我认为这是因为俄文字母的原因。

回答

1

试试这个:

from os import listdir 
from os.path import isfile 

for filepath in listdir("/path/to/folder") 
    if isfile(filepath): # if need 
     last_five_lines = open(filepath).readlines()[-15:] 

# or, one line: 

x = [open(f).readlines()[-15:] for f in listdir("/path/to/folder") if isfile(f)] 

更新时间:

lastlines = [] 
for file in files: 
    lastlines += open(join(dir_path, file), "r").readlines()[-15:] 
with open('./fin.txt', 'w') as f: 
    f.writelines(lastlines) 
+0

嗯......只要确保没有任何文件过大,这应该能正常运行。 – mgilson

+0

这段代码很好,但是由于我在编辑时遇到了写入文件的错误。 – Andrej

+1

使用'out + = filedata'而不是'out.append(filedata)'。 – defuz

0
from os import listdir 
from os.path import isfile, join 

dir_path= '/usr/lib/something' 
files = [ f for f in listdir(dir_path) if isfile(join(dir_path,f)) ] 

for file in files: 
    filedata = open(join(dir_path, file), "r").readlines()[-15:] 
    #do something with the filedata 
7
import os 
from collections import deque 

for filename in os.listdir('/some/path'): 
    # might want to put a check it's actually a file here... 
    # (join it to a root path, or anything else....) 
    # and sanity check it's text of a usable kind 
    with open(filename) as fin: 
     last_15 = deque(fin, 15) 

deque会自动丢弃最早的条目和峰的最大尺寸是15,所以它是一个保持“最后”'n'项的有效方式。

+0

只是一个风格问题,也许'与开放(文件名)为f:last15 = deque(f,15)' – mgilson

+0

@mgilson Yup-我只是懒惰 - 编辑。谢谢。 –

+0

@mgilson感谢您的编辑。这有点让我大开眼界! –

0

希望这有助于:

import os 

current_dir = os.getcwd() 
dir_objects = os.listdir(current_dir) 
dict_of_last_15 = {} 
for file in dir_objects: 
    file_obj = open(file, 'rb') 
    content = file_obj.readlines() 
    last_15_lines = content[-15:] 
    dict_of_last_15[file] = last_15_lines 
    print "#############: %s" % file 
    print dict_of_last_15[file] 
    file_to_check.close() 
相关问题