[英]Python use for loop to read specific multiply lines from txt files
I want use python to read specific multiply lines from txt files. 我想使用python从txt文件读取特定的乘法行。 For example ,read line 7 to 10, 17 to 20, 27 to 30 etc. 例如,读取第7至10行,17至20行,27至30行等。
Here is the code I write, but it will only print out the first 3 lines numbers. 这是我编写的代码,但只会打印出前3行的数字。 Why? 为什么? I am very new to use Python. 我刚开始使用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]
This simplifies the math a little to choose the relevant lines. 选择相关行会稍微简化数学运算。 You don't need to use readlines()
. 您不需要使用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
You should only call readlines() once, so you should do it outside the loop: 您应该只调用一次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
You can use a combination list slicing and comprehension. 您可以使用组合列表切片和理解。
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)]
This will return a list of lists containing each group of lines (ie 7 thru 10, 17 thru 20). 这将返回包含每行行的列表列表(即7至10、17至20)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.