我是Python的新手,所以请帮帮我... 我想在文本文件中取出每个第3行,第4行和第5行。文本文件中有22行 这只是一个算法
For i in range (0,16):
Name = Extract line 3 from text file.
Distance= Extract line 4 from text file.
Time = Extract line 5 from text file.
Calculations = (Distance/Time )
Print (Name,Calculations, Time)
Name = ''
Distance = ''
Time = ''
我的问题是我希望for循环重复,但下次名称应该提取第6行,距离第7行和时间线8.下一次循环重复时,它应该将名称更改为第9行,依此类推。 .. 希望我的问题很清楚,我不知道该怎么说。 感谢所有的帮助提前...我无能为力
顺便说一句,我使用的是python 3.3
答案 0 :(得分:0)
f = open('file.txt')
count = 0 #where in the file we are
entry = 3 #the first line we want to write, e.g Name
for line in f:
count += 1
if count == entry: name = line.strip() #name
elif count == entry+1: distance = line.strip() #distance
elif count == entry+2:
time = line.strip() #time
entry += 3 #now we've hit time, lets set entry to line 6 for the next iteration
calculation = float(distance) / float(time)
print name, calculation, time
#do calculations
答案 1 :(得分:0)
如果你总是知道你只需要这三行,你只需要这样做:
values = list()
state = 0 # 0 is name, 1 is distance, 2 is time
line_num = 0
with open(filename) as ifile:
name, distance, time = '',0,0 # the null set
for line in ifile:
if line_num < 3:
line_num += 1
else:
if state == 0:
name = line.strip()
state = 1
elif state == 1:
distance = float(line.strip())
state = 2
elif state == 2:
time = float(line.strip())
state = 0
values.append((name, distance, time))
for name, distance, time in values:
# do calculations on name, distance, time
答案 2 :(得分:0)
使用itertools中的石斑鱼配方:
from itertools import zip_longest
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
with open('file.txt') as ff:
data = ff.read().split('\n')[2:]
data = grouper(data, 3, None)
for name, distance, time in data:
print(name, int(distance)/int(time), time)
答案 3 :(得分:0)
你的文件不是很大(只有几行),所以内存似乎不是你的问题。说,你可以尝试不同的方法:
lines = []
with open("file.txt") as input:
lines = input.readlines() # If file is large is not a good idea load it all into memory.
thirds = lines[2:-1:3] # Select from third element to the end and step by 3
fourths = lines[3:-1:3] # Select from fourth element to the end and step by 3
fifths = lines[4:-1:3] # Select from fifth element to the end and step by 3
for (name, distance, time) in zip(thirds, fourths, fifths):
calculations = distance / time
print(name, calculations, time)
答案 4 :(得分:0)
以下代码打开您的文件,通过合理猜测您的描述使用第1行和第2行,然后继续扫描文件
方法readline
会从文件中返回一行,最后会有换行符(这就是我们在使用文件时使用方法strip
的原因内容作为名称...)并在达到EOF时仅返回空字符串''
(仅)。
我们使用无限循环来扫描文件的其余部分,但是当文件结束时我们想要停止...这就是为什么当我们读取活动名称时我们做了不同的事情,首先我们测试一个空字符串(意思是:我们达到了EOF)并且可能会脱离循环。
with open('data.txt') as data:
person = data.readline().strip()
age = int(data.readline())
while True:
activity = data.readline()
if not activity:
break
activity = activity.strip()
distance = float(data.readline())
time = float(data.readline())
velocity = distance/time
format_output()
答案 5 :(得分:0)
我认为这样的事情是一种快速而简单的方法:
# create test file
with open('3_lines_test.txt', 'wt') as file:
for i in range(1, 22):
file.write('line{:>2}\n'.format(i))
# read test file
with open('3_lines_test.txt', 'rt') as file:
for _ in range(3): next(file) # skip first 3 lines
while True:
try:
name = next(file).rstrip() # read next 3 lines
dist = next(file).rstrip() # "
time = next(file).rstrip() # "
except StopIteration:
break
# do calculations or whatever...
print('values: ({name!r}, {dist!r}, {time!r})'.format(**locals()))
print('done')
输出:
values: ('line 4', 'line 5', 'line 6')
values: ('line 7', 'line 8', 'line 9')
values: ('line10', 'line11', 'line12')
values: ('line13', 'line14', 'line15')
values: ('line16', 'line17', 'line18')
values: ('line19', 'line20', 'line21')
done
对于这样一个短文件,您可以只显式读取每一行并计算值6次而不需要任何循环。这将需要更多的代码,但其中大部分都是锅炉板,它可能是最快的方法。