繁体   English   中英

如何获取文本文件中的第三行,然后获取第三行的值,再获取下一行?

[英]How can I take every 3rd line in a text file, then after taking the value of line 3, take the next one?

我是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

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

如果您始终知道只需要这三行,则只需执行以下操作:

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

使用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)

您的文件不是很大(只有几行),因此内存似乎对您来说不是问题。 话虽如此,您可以尝试另一种方法:

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)

以下代码打开您的文件,通过合理地猜测您的描述使用#1和#2行,然后继续扫描文件

  1. 方法readline从文件中返回一行,并在末尾添加换行符(这就是为什么当我们要使用文件内容作为名称时使用方法strip的原因...),并且仅返回一个空字符串'' )到达EOF时。

  2. 我们使用无限循环来扫描文件的其余部分,但是当文件结束时,我们要停止...这就是为什么我们在读取活动名称时做不同的事情的原因,首先我们测试一个空字符串(意思是:达到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()

我认为类似这样的方法将是一种快速而简单的方法:

# 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次值,而无需任何循环。 这将需要更多代码,但是其中大多数将是样板代码,并且可能是最快的方法。

暂无
暂无

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

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