Skip to main content
 首页 » 编程设计

python之使用 python 从目录中的所有 .txt 文件中获取行

2025年05月04日12zhwl

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

我选择了这段代码:

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() 

但我收到错误“TypeError:writelines() 参数必须是字符串序列”。我认为这是因为行中有俄文字母。

请您参考如下方法:

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' 个项目的有效方法。