简体   繁体   English

如何在python中跳过文件的第一行

[英]how to skip the first line of a file in python

I need to write a code to read a .txt file, which is a matrix displayed as below, and turn it into an new integer list matrix. 我需要编写代码以读取.txt文件,该文件是如下所示的矩阵,并将其转换为新的整数列表矩阵。 However, I want to skip first line of this .txt file without manually deleting the file. 但是,我想跳过此.txt文件的第一行,而无需手动删除该文件。 I do not know how to do that. 我不知道该怎么做。 I have written some code. 我已经写了一些代码。 It is able to display the matrix, but I am unable to get rid of the first line: 它能够显示矩阵,但是我无法摆脱第一行:

def display_matrix(a_matrix):
    for row in a_matrix:
        print(row)
    return a_matrix

def numerical_form_of(a_list):
    return [int(a_list[i]) for i in range(len(a_list))]

def get_scoring_matrix():
    scoring_file = open("Scoring Matrix")
    row_num = 0
    while row_num <= NUMBER_OF_FRAGMENTS:
        content_of_line = scoring_file.readline()
        content_list = content_of_line.split('   ')
        numerical_form = numerical_form_of(content_list[1:])
        scoring_matrix = []
        scoring_matrix.append(numerical_form)
        row_num += 1
        #print(scoring_matrix)
        display_matrix(scoring_matrix)
    # (Complement): row_num = NUMBER_OF_FRAGMENTS
    return scoring_matrix

get_scoring_matrix()

Scoring Matrix is a .txt file: 
    1   2   3   4   5   6   7
1   0   1   1   1   1   1   1
2   0   0   1   1   1   1   1
3   0   0   0   1   1   1   1
4   0   0   0   0   1   1   1
5   0   0   0   0   0   1   1
6   0   0   0   0   0   0   1
7   0   0   0   0   0   0   0

The result of my code: 
[1, 2, 3, 4, 5, 6, 7]
[0, 1, 1, 1, 1, 1, 1]
[0, 0, 1, 1, 1, 1, 1]
[0, 0, 0, 1, 1, 1, 1]
[0, 0, 0, 0, 1, 1, 1]
[0, 0, 0, 0, 0, 1, 1]
[0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 0, 0]

只需在while循环之前放置一个scoring_file.readline()即可。

I suggest using an automated tool: 我建议使用自动化工具:

import pandas
df = pandas.read_table("Scoring Matrix", delim_whitespace = True)

If you insist doing it yourself, change the while loop; 如果您坚持要自己做,请更改while循环;

while row_num <= NUMBER_OF_FRAGMENTS:
        content_of_line = scoring_file.readline()
        if row_num == 0:
            content_of_line = scoring_file.readline()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM