【问题标题】:How to Delete First Few Rows of .txt File in Python?如何在 Python 中删除 .txt 文件的前几行?
【发布时间】:2021-02-01 12:48:23
【问题描述】:

我有一个 .txt 文件,如下所示:

# Explanatory text
# Explanatory text
# ID_1 ID_2
10310   34426
104510  4582343
1032410 5424233
12410   957422

文件中同一行的两个ID用制表符分隔,制表符编码为'\t'

我正在尝试使用数据集中的数字进行一些分析,因此想删除前三行。如何在 Python 中做到这一点? IE。我想生成一个新的数据集,如下所示:

10310   34426
104510  4582343
1032410 5424233
12410   957422

我尝试了以下代码,但没有成功:

f = open(filename,'r')
lines = f.readlines()[3:]
f.close()

它不起作用,因为我得到了这种格式(一个列表,存在 \t 和 \n),而不是我在上面指出的那种:

[10310\t34426\n', '104510\t4582343\n', '1032410\t5424233\n' ... ]

【问题讨论】:

  • 如果它以#开头,你可以忽略它
  • 您可能想说的不仅仅是“它不起作用”,
  • readlines 从零开始。使用lines = f.readlines()[3:]
  • 什么不起作用?你得到了什么输出?你期待什么?
  • 如果您在 EDA 中使用 pandas,则 pandas.read_csv 中有一个 skiprows 参数,pandas.read_csv(filepath_or_buffer, delimiter='\t,skiprows=2)

标签: python txt


【解决方案1】:

好的,解决方法如下:

with open('file.txt') as f:
    lines = f.readlines()

lines = lines[3:]

删除评论

此函数删除所有注释行

def remove_comments(lines):
    return [line for line in lines if line.startswith("#") == False]

删除 n 条顶行

def remove_n_lines_from_top(lines, n):
    if n <= len(lines):
        return lines[n:]
    else:
        return lines

这里是完整的源代码:

with open('file.txt') as f:
    lines = f.readlines()


def remove_comments(lines):
    return [line for line in lines if line.startswith("#") == False]

def remove_n_line(lines, n):
    return lines[n if n<= len(lines) else 0:]

lines = remove_n_lines_from_top(lines, 3)

f = open("new_file.txt", "w+") # save on new_file
f.writelines(lines)
f.close()

【讨论】:

    【解决方案2】:

    您可以使用 Python 的Pandas 轻松完成这些任务:

    import pandas as pd
    
    pd.read_csv(filename, header=None, skiprows=[0, 1, 2], sep='\t')
    

    【讨论】:

    • 这个答案具有误导性......他会认为 pndas 是一个文件管理器库
    【解决方案3】:

    你可以试试这样的

    with open(filename,'r') as fh
    
        for curline in fh:
    
             # check if the current line
             # starts with "#"
    
             if curline.startswith("#"):
                ...
                ...
             else:
                ...
                ...
    

    【讨论】:

      猜你喜欢
      • 2018-03-16
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      相关资源
      最近更新 更多