【问题标题】:Extracting first 2 rows and last row from .txt or .csv Python从 .txt 或 .csv Python 中提取前 2 行和最后一行
【发布时间】:2017-02-16 08:20:36
【问题描述】:

我需要从大量 .txt 和 .csv 文件中提取前 2 行和最后一行。如何允许用户选择一个文件并输出一个新的 .txt 或 .csv 文件,其中只有这 3 行?

【问题讨论】:

    标签: python csv extract


    【解决方案1】:

    这是你需要的:

    def extract_lines(filename,outputname):
        l = []
        with open(filename,'r') as f: 
            for index,line in enumerate(f): #This iterates the file line by line which is memory efficient in case the csv is huge.
                if index < 2: #first 2 lines
                    l.append(line)
            if index > 1: # means the file has at least 3 lines
                l.append(line)
        with open(outputname,'w') as f:
            for line in l:
                f.write(line)
    

    【讨论】:

    • @Adirio 不。它意味着在循环之外。 If 语句检查文件中的行数至少为 3 行。如果文件只有 2 行,则没有必要添加“last”行,因为前 2 行包含“last”。
    • 没错,我的错。实际上,我会通过从循环中读取前 2 行并立即丢弃循环来提高效率。这样,if 就不需要对每一行都进行评估,这对于大文件可能需要一些时间。
    • @Adirio,真的。如果问题提到最快的方式,我可能会改用seek
    【解决方案2】:
    def get_lines(filename, front=2, rear=1):
        result = []
        with open(filename, 'rb') as f:
            for i, val in enumerate(f):
                if i >= front:
                    break
                result.append(val)
    
            back_pos = -2
            f.seek(back_pos, 2)  # jump to the second end byte
    
            rear_count = 0
            while True:
                if '\n' in f.read(1):
                    rear_count += 1
    
                if rear_count >= rear:
                    result.extend(f.readlines())
                    break
    
                back_pos -= 1
                f.seek(back_pos, 2)
    
        return result
    

    阅读第一行很容易,但很难阅读最后一行。 迭代行非常慢。

    【讨论】:

      【解决方案3】:

      我想你也可以使用 bash 脚本来实现这个需求。

      #!/bin/bash
      
      for file in $(find . -name '*.txt' -o -name '*.csv' )
      do
          sed -n -e '1,2p' -e '$p' ${file} > "result"${file:(-5)}
      done
      

      此脚本将搜索所有以 txt 或 csv 结尾的文件。它会剪切前两行和最后一行,将这些行存储在一个新文件中。

      比如我有三个文件,分别命名为file1.txt、file2.txt、file3.csv,它会为每个文件剪掉三行,分别存放在result1.txt、result2.txt、result3.csv中。

      【讨论】:

        【解决方案4】:

        这样你就可以返回你想要的行,只是使用范围的问题

        df=open(r"D:\...\nameFile.txt",encoding='utf8')
        
        def etiqueta(df):
            lista=[]
            for line,x in zip(df,range(0,2)):
                lista.append(line)
            return lista
        
        etiqueta(df)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-28
          • 2016-06-13
          • 1970-01-01
          • 1970-01-01
          • 2017-10-02
          • 1970-01-01
          相关资源
          最近更新 更多