脚本不使用conu在多行上迭代

2024-10-06 06:54:19 发布

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

我有一个脚本,python应该一次处理每一行,并做很多事情(对齐和协同),所以我尝试使用count来迭代输入文件中的每一行。你知道吗

但是,当我运行它时,它只使用输入文件的最后一行,并使用它运行其余的行,直到结束。所以脚本是好的,但不是所有 对于测试,我只尝试了4行,这是脚本的迭代部分:

for line in open(sys.argv[1]):
     count+=1
     if count < 4 :
         continue
     elif count > 4 :
         break

我试着写一个测试脚本,看看它是否每行都运行:

count = 0
file = open('mclOutput2', 'r') 
while True:
    count+=1
    if count < 4:
        print file.readlines()
    elif count > 4 :
        break

这是我得到的结果

['mono|comp78360_c0_seq1\tpoly|comp71317_c0_seq1\tturc|comp70178_c0_seq1\tturc|comp19023_c0_seq1\n', 'mono|comp78395_c0_seq1\trubr|comp23732_c0_seq1\trugi|comp32227_c0_seq1\tsulc|comp11641_c0_seq1\n', 'mono|comp80301_c0_seq1\tnegl|comp30782_c0_seq1\tphar|comp29363_c0_seq1\tpoly|comp53026_c0_seq2\n', 'mono|comp80554_c0_seq1\tnegl|comp27459_c0_seq1\tpoly|comp57863_c0_seq2\trugi|comp11691_c0_seq1\n']
[]
[]

我真的不知道如何修复它,有什么想法我做错了什么?你知道吗


Tags: 文件脚本ifcountopenfilebreakelif
2条回答

更好的代码:

from itertools import islice

def skip_lines(inf, n):
    list(islice(inf, n))

with open(sys.argv[1]) as inf:
    skip_lines(inf, 4)
    for count,line in enumerate(inf, 4):
        print("do your stuff here")

编辑:查看您的数据(在.readlines输出中引用),您希望

GET_LINES = 4
with open(sys.argv[1]) as inf:
    for count,line in zip(range(1, GET_LINES+1), inf):
        data = [pairs.split('|') for pairs in line.strip().split('\t')]
        print("{:>3d}: {}".format(count, data))

这给了

  1: [['mono', 'comp78360_c0_seq1'], ['poly', 'comp71317_c0_seq1'], ['turc', 'comp70178_c0_seq1'], ['turc', 'comp19023_c0_seq1']]
  2: [['mono', 'comp78395_c0_seq1'], ['rubr', 'comp23732_c0_seq1'], ['rugi', 'comp32227_c0_seq1'], ['sulc', 'comp11641_c0_seq1']]
  3: [['mono', 'comp80301_c0_seq1'], ['negl', 'comp30782_c0_seq1'], ['phar', 'comp29363_c0_seq1'], ['poly', 'comp53026_c0_seq2']]
  4: [['mono', 'comp80554_c0_seq1'], ['negl', 'comp27459_c0_seq1'], ['poly', 'comp57863_c0_seq2'], ['rugi', 'comp11691_c0_seq1']]

file.readline代替file.readlines

请注意,file是python内置的,最好不要将其用作变量名

相关问题 更多 >