跳过一行python打开

2024-06-26 17:49:25 发布

您现在位置:Python中文网/ 问答频道 /正文

如何跳过第一行标题?我在后面的代码中有重复的头,所以我可以通过如果不是l.startswith('MANDT')而是我想保留的第一个头来消除它们。我需要如何修改代码?在

keep -> MANDT|BUKRS|NETWR|UMSKS|UMSKZ|AUGDT|AUGBL|ZUONR
100|1000|23.321-|||||TEXT
100|1000|0.12|||||TEXT
100|1500|90|||||TEXT
remove -> MANDT|BUKRS|NETWR|UMSKS|UMSKZ|AUGDT|AUGBL|ZUONR
100|1000|23.321-|||||TEXT
100|1000|0.12|||||TEXT
100|1500|90|||||TEXT
remove -> MANDT|BUKRS|NETWR|UMSKS|UMSKZ|AUGDT|AUGBL|ZUONR

我正在使用的代码。在

^{pr2}$

Tags: 代码text标题removekeepstartswithpr2mandt
3条回答

只需使用切片:

for l in lines[1:]:
  # do stuff

有很多方法。我可以从一个简单的变量开始,它跟踪第一个标题行是否被看到。在

expected_header = 'MANDT|BUKRS...'

with open('yourfile.txt', 'r+') as f:   # 'r+' - read/write mode
    # ... get lines ...

header_seen = False
for l in lines:
    if l == expected_header:
        if header_seen:
            # do nothing, just skip to the next line in the file
            continue
        else:
             # act on this line, but remember not to parse further headers
            header_seen = True 
    # do something with the line here

你可以试试这个:

f = [i.strip("\n") for i in open('filename.txt')]
new_file = [f[0]]+[i for i in f[1:] if i != f[0]]

相关问题 更多 >