[英]how to skip the first line of a file in python
我需要編寫代碼以讀取.txt文件,該文件是如下所示的矩陣,並將其轉換為新的整數列表矩陣。 但是,我想跳過此.txt文件的第一行,而無需手動刪除該文件。 我不知道該怎么做。 我已經寫了一些代碼。 它能夠顯示矩陣,但是我無法擺脫第一行:
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()即可。
我建議使用自動化工具:
import pandas
df = pandas.read_table("Scoring Matrix", delim_whitespace = True)
如果您堅持要自己做,請更改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.