用python从文件中读取数据,但始终从文件中获取特定数据

用python从文件中读取数据,但始终从文件中获取特定数据,python,Python,您好,我正在尝试从.dat文件读取数据,该文件包含以下信息: 1 Carmella Henderson 24.52 13.5 21.76 2 Christal Piper 14.98 11.01 21.75 3 Erma Park 12.11 13.51 18.18 4 Dorita Griffin 20.05 10.39 21.35 5 Marlon Holmes 18.86 13.02 13.36 根据这些数据,我需要人名、姓名和第一个号码,如下所示: 1 #person number

您好,我正在尝试从.dat文件读取数据,该文件包含以下信息:

1
Carmella Henderson
24.52
13.5
21.76
2
Christal Piper
14.98
11.01
21.75
3
Erma Park
12.11
13.51
18.18
4
Dorita Griffin
20.05
10.39
21.35
5 
Marlon Holmes
18.86
13.02
13.36
根据这些数据,我需要人名、姓名和第一个号码,如下所示:

1 #person number
Marlon Holmes  #Name
18.86 # First number
13.02
13.36
然而,目前我的代码正在读取文件中的数据,而不是这些特定部分,它只是打印文件

这是我目前针对此特定部分的代码:

def Cucumber_Scoreboard():
    with open('veggies_2015.dat', 'r') as f:
        count = 0
        for line in f:
            count **= 1
            if count % 2 == 0:
                print (line)
我不确定哪里出了问题,我试着把文件中的数据放到一个列表中,并从那里尝试,但没有成功,任何帮助都将不胜感激

完整文件代码(如果需要):

def menu():
    exit = False


    while not exit:
        print("To enter new competitior data, type new")
        print("To view the competition score boards, type Scoreboard")
        print("To view the Best Overall Growers Scoreboard, type Podium")
        print("To review this years and previous data, type Data review")
        print("Type quit to exit the program")

        choice = raw_input("Which option would you like?")

        if choice == 'new':
            new_competitor()
        elif choice == 'Scoreboard':
            scoreboard_menu()
        elif choice == 'Podium':
            podium_place()
        elif choice == 'Data review':
            data_review()
        elif choice == 'quit':
            print("Goodbye")
            raise SystemExit

"""Entering new competitor data: record competitor's name and vegtables lengths"""

def competitor_data():
    global competitor_num
    l = []

    print("How many competitors would you like to enter?")

    competitors = raw_input("Number of competitors:")

    num_competitors = int(competitors)

    for i in range(num_competitors):

        name = raw_input("Enter competitor name:")
        Cucumber = raw_input("Enter length of Cucumber:")
        Carrot = raw_input("Enter length of Carrot:")
        Runner_Beans = raw_input("Enter length of Runner Beans:")

        l.append(competitor_num)
        l.append(name)
        l.append(Cucumber)
        l.append(Carrot)
        l.append(Runner_Beans)

        competitor_num += 1

    return (l)



def new_competitor():
    with open('veggies_2016.txt', 'a') as f:
        for item in competitor_data():
            f.write("%s\n" %(item))



def scoreboard_menu():
    exit = False

    print("Which vegetable would you like the scoreboard for?")

    vegetable = raw_input("Please type either Cucumber, Carrot or Runner Beans:")

    if vegetable == "Cucumber":
        Cucumber_Scoreboard()
    elif vegetable == "Carrot":
        Carrot_Scoreboard()
    elif vegetable == "Runner Beans":
        Runner_Beans_Scoreboard()

def Cucumber_Scoreboard():
    with open('veggies_2015.dat', 'r') as f:
        count = 0
        for line in f:
            count **= 1
            if count % 2 == 0:
                print (line)

您可以让程序逐行读取整个文件,以获取所有信息。然后,因为数据的格式是已知的(例如位置、名称…),请使用file.readline()跳过不需要的行,这会将您移到下一行。

您可以让程序逐行读取整个文件,以获取所有信息。然后,由于数据的格式已知(例如位置、名称…),请使用file.readline()跳过不需要的行,这会将您移到下一行。

创建一个函数,一次读取一条“记录”(5行),然后重复调用它:

def read_data(in_file):
    rec = {}
    rec["num"] = in_file.next().strip()
    rec["name"] = in_file.next().strip()
    rec["cucumber"] = float(in_file.next().strip())

    # skip 2 lines
    in_file.next()
    in_file.next()

    return rec
编辑:改进代码+添加用法示例

read_data()
函数从文件中读取一条5行记录,并将其数据作为字典返回。使用此功能的示例如下:

def Cucumber_Scoreboard():
    with open('veggies_2015.dat', 'r') as in_file:
        data = []

        try:
            while True:
                rec = read_data(in_file)
                data.append(rec)

        except StopIteration:
            pass

    data_sorted = sorted(data, key = lambda x: x["cucumber"])

    return data_sorted

cucumber = Cucumber_Scoreboard()

from pprint import pprint
pprint(cucumber)

创建一个每次读取一条“记录”(5行)的函数,然后重复调用它:

def read_data(in_file):
    rec = {}
    rec["num"] = in_file.next().strip()
    rec["name"] = in_file.next().strip()
    rec["cucumber"] = float(in_file.next().strip())

    # skip 2 lines
    in_file.next()
    in_file.next()

    return rec
编辑:改进代码+添加用法示例

read_data()
函数从文件中读取一条5行记录,并将其数据作为字典返回。使用此功能的示例如下:

def Cucumber_Scoreboard():
    with open('veggies_2015.dat', 'r') as in_file:
        data = []

        try:
            while True:
                rec = read_data(in_file)
                data.append(rec)

        except StopIteration:
            pass

    data_sorted = sorted(data, key = lambda x: x["cucumber"])

    return data_sorted

cucumber = Cucumber_Scoreboard()

from pprint import pprint
pprint(cucumber)

这并不是最优雅的方式,但是如果你要一行一行地去做,你需要一个额外的计数器,在重置你的计数器之前,这会导致设置数量的“多余”行没有发生任何事情。请注意,
oversed_count
只需增加一次,因为您希望最终的
else
重置两个计数器,这同样不会导致打印内容,但仍会导致跳过行

def Cucumber_Scoreboard():
    with open('name_example.txt', 'r') as f:
        count = 0
        excess_count = 0
        for line in f:
            if count < 3:
                print (line)
                count += 1
            elif count == 3 and excess_count < 1:
                excess_count += 1
            else:
                count = 0
                excess_count = 0
def Cucumber_记分板():
以open('name_example.txt','r')作为f:
计数=0
超额计数=0
对于f中的行:
如果计数小于3:
打印(行)
计数+=1
elif计数==3且超出的_计数<1:
超出计数+=1
其他:
计数=0
超额计数=0
编辑:根据你的评论,我扩展了这个答案。实际上,你所问的应该作为另一个问题提出,因为它与你的主要问题无关。正如jDo所指出的,这不是理想的代码,因为如果有一个空行或丢失的数据导致一行被人为跳过,它将立即失败。另外,新的代码被塞进了我最初的答案中。仅将此用作重置循环中的计数器和列表的说明,对于严重的情况,它是不稳定的

from operator import itemgetter

def Cucumber_Scoreboard():
    with open('name_example.txt', 'r') as f:
        count = 0
        excess_count = 0
        complete_person_list = []
        sublist = []

        for line in f:
            if count < 3:
                print (line)
                sublist.append(line.replace('\n', ''))
                count += 1
            elif count == 3 and excess_count < 1:
                excess_count += 1
            else:
                count = 0
                excess_count = 0
                complete_person_list.append(sublist)
                sublist = []

        sorted_list = sorted(complete_person_list, key=itemgetter(2), reverse = True)
    return sorted_list

a = Cucumber_Scoreboard()
从操作员导入itemgetter
def CUMBURE_记分板():
以open('name_example.txt','r')作为f:
计数=0
超额计数=0
完成人员列表=[]
子列表=[]
对于f中的行:
如果计数小于3:
打印(行)
子列表.append(第.replace行('\n','')
计数+=1
elif计数==3且超出的_计数<1:
超出计数+=1
其他:
计数=0
超额计数=0
完成人员列表。追加(子列表)
子列表=[]
已排序的列表=已排序(完整的人员列表,键=itemgetter(2),反向=True)
返回已排序的列表
a=黄瓜记分板()

这并不是最优雅的方式,但是如果你要逐行进行,你需要一个额外的计数器,在重置计数器之前,它会导致设置数量的“多余”行不发生任何事情。请注意,
oversed_count
只需增加一次,因为您希望最终的
else
重置两个计数器,这同样不会导致打印内容,但仍会导致跳过行

def Cucumber_Scoreboard():
    with open('name_example.txt', 'r') as f:
        count = 0
        excess_count = 0
        for line in f:
            if count < 3:
                print (line)
                count += 1
            elif count == 3 and excess_count < 1:
                excess_count += 1
            else:
                count = 0
                excess_count = 0
def Cucumber_记分板():
以open('name_example.txt','r')作为f:
计数=0
超额计数=0
对于f中的行:
如果计数小于3:
打印(行)
计数+=1
elif计数==3且超出的_计数<1:
超出计数+=1
其他:
计数=0
超额计数=0
编辑:根据你的评论,我扩展了这个答案。实际上,你所问的应该作为另一个问题提出,因为它与你的主要问题无关。正如jDo所指出的,这不是理想的代码,因为如果有一个空行或丢失的数据导致一行被人为跳过,它将立即失败。另外,新的代码被塞进了我最初的答案中。仅将此用作重置循环中的计数器和列表的说明,对于严重的情况,它是不稳定的

from operator import itemgetter

def Cucumber_Scoreboard():
    with open('name_example.txt', 'r') as f:
        count = 0
        excess_count = 0
        complete_person_list = []
        sublist = []

        for line in f:
            if count < 3:
                print (line)
                sublist.append(line.replace('\n', ''))
                count += 1
            elif count == 3 and excess_count < 1:
                excess_count += 1
            else:
                count = 0
                excess_count = 0
                complete_person_list.append(sublist)
                sublist = []

        sorted_list = sorted(complete_person_list, key=itemgetter(2), reverse = True)
    return sorted_list

a = Cucumber_Scoreboard()
从操作员导入itemgetter
def CUMBURE_记分板():
以open('name_example.txt','r')作为f:
计数=0
超额计数=0
完成人员列表=[]
子列表=[]
对于f中的行:
如果计数小于3:
打印(行)
子列表.append(第.replace行('\n','')
计数+=1
elif计数==3且超出的_计数<1:
超出计数+=1
其他:
计数=0
超额计数=0
完成人员列表。追加(子列表)
子列表=[]
已排序的列表=已排序(完整的人员列表,键=itemgetter(2),反向=True)
返回已排序的列表
a=黄瓜记分板()
最近有人