【问题标题】:Get rows from all .txt files in directory using python使用python从目录中的所有.txt文件中获取行
【发布时间】:2012-10-10 14:09:27
【问题描述】:

我在一个目录中有一些 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() 参数必须是字符串序列”。我认为这是因为行中的俄罗斯字母。

【问题讨论】:

    标签: python find


    【解决方案1】:
    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”个项目的有效方法。

    【讨论】:

    • 只是风格问题,可能是with open(filename) as f: last15 = deque(f,15)
    • @mgilson 感谢您的编辑。这让我有点脑残!
    【解决方案2】:

    试试这个:

    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)
    

    【讨论】:

    • 嗯...只要确保所有文件都没有太大,这应该可以正常工作。
    • 这段代码很好,但是当我编辑有问题时,写入文件时出错。
    • 使用out += filedata 代替out.append(filedata)
    【解决方案3】:
    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
    

    【讨论】:

      【解决方案4】:

      希望这会有所帮助:

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

      【讨论】:

        猜你喜欢
        • 2017-01-21
        • 2014-05-20
        • 2021-11-06
        • 2023-03-26
        • 2016-02-03
        • 1970-01-01
        • 2010-11-28
        • 1970-01-01
        • 2014-01-18
        相关资源
        最近更新 更多