如何使用文件中的特定行并在Python中打印出来

时间:2014-11-25 00:07:20

标签: python

我有一个最终项目。这是绊倒我的部分。如果最后一个数字超过750,我需要弄清楚如何从文件中拉出整行。文件如下所示:

A 500 600 700 144.666

然后你告诉它多次,直到J或Q或F或其他什么。如果第四个数字超过750,那么我必须打印整行。要求如下:

将警报信息打印到屏幕上,小行星的X,Y和Z位置在小于750 km的距离内。

对于最近的小行星,向控制台发送警报消息,然后发出7声嘟嘟声(实际发出哔哔声)。

警报消息可能如下所示:小数点后只有两位数。

Warning  -  Warning  - Warning
Nearest asteroid B at ??, ??, ??: ?? km away 
Time to impact ??? seconds
asteroid B at at ??, ??, ??: ?? km away
asteroid D at at ??, ??, ??: ?? km away

我还没有接近声音部分,我只需要弄清楚如何打印整条线。我假设一个for循环或if语句?这是我第一次编程,所以我有点迷失。

3 个答案:

答案 0 :(得分:0)

with open("path/to/your_file") as f:
    for line in f: # loop over every line
        spl = line.split()
        if float(spl[4]) > 750:# split on whitespace and check if fourth/last digit is > 750
            print(line)
        else:
            print("Alarm! asteroid within 750km, position {} {} {}".format(spl[1],spl[2],spl[3]))
In [4]: line  = "A 500 600 700 144.666"

In [5]: line.split() # splits into individual elements
Out[5]: ['A', '500', '600', '700', '144.666']

In [6]: float(line.split()[4]) # casts the string to a float
Out[6]: 144.666

您必须投放到float,因为int('144.666')会抛出错误,750.1 > 750

如果您在Windows上,可以使用winsound作为警报

1https://docs.python.org/2/library/winsound.htmlpyglet似乎跨平台

答案 1 :(得分:0)

import csv

with open('path/to/file') as infile:
    for row in csv.reader(infile, delimiter=' '):
        if int(row[4]) > 750:
            print(' '.join(row))

答案 2 :(得分:0)

首先你要读这样的文件

with open('file.txt') as f:
    for line in f:
        ##split the line by your deliminator (assumming it is tab delimitated), this will return a list 
        fields = line.split('\t')
        ### determine if fields[4] which correspond to the 5th column (python list are 0 based) 
        if (int(fields[4]) > 750) 
            print(line)