簡體   English   中英

Python使用for循環從txt文件讀取特定的乘法行

[英]Python use for loop to read specific multiply lines from txt files

我想使用python從txt文件讀取特定的乘法行。 例如,讀取第7至10行,17至20行,27至30行等。

這是我編寫的代碼,但只會打印出前3行的數字。 為什么? 我剛開始使用Python。

with open('OpenDR Data.txt', 'r') as f:  
    for poseNum in range(0, 4):               
        Data = f.readlines()[7+10*poseNum:10+10*poseNum] 
        for line in Data: 
            matAll = line.split()    
            MatList = map(float, matAll) 
            MatArray1D = np.array(MatList)
            print MatArray1D
with open('OpenDR Data.txt') as f:
    lines = f.readlines()

for poseNum in range(0, 4):               
    Data = lines[7+10*poseNum:10+10*poseNum]

選擇相關行會稍微簡化數學運算。 您不需要使用readlines()

with open('OpenDR Data.txt', 'r') as fp:
    for idx, line in enumerate(fp, 1):
        if idx % 10 in [7,8,9,0]:
            matAll = line.split()    
            MatList = map(float, matAll) 
            MatArray1D = np.array(MatList)
            print MatArray1D

您應該只調用一次readlines(),所以您應該在循環外執行此操作:

with open('OpenDR Data.txt', 'r') as f:  
    lines = f.readlines()
    for poseNum in range(0, 4):               
        Data = lines[7+10*poseNum:10+10*poseNum] 
        for line in Data: 
            matAll = line.split()    
            MatList = map(float, matAll) 
            MatArray1D = np.array(MatList)
            print MatArray1D

您可以使用組合列表切片和理解。

start = 7
end = 10
interval = 10
groups = 3

with open('data.txt') as f:
    lines = f.readlines()
    mult_lines = [lines[start-1 + interval*i:end + interval*i] for i in range(groups)]

這將返回包含每行行的列表列表(即7至10、17至20)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM