Python归档 - 需要帮助(初学者的东西)

时间:2014-02-11 15:45:55

标签: python file

我最近开始学习python文件,所以我不是那么好,这就是为什么我需要你帮助我正在尝试创建的这个基本文件程序。
基本上,我以这种格式输入名字,姓氏,年龄,分数:
例如:

John    Smith    17    22 (the spaces are tabs)
Tom     Jones    34    18
Lewis   Martins  23    20

到目前为止,我已经创建了这个,但它只能得到第一个得分,但我需要得到所有这些:

    F = open('Program File','r')

    score_string = ''
    count = 0

    while count < 3:
        readit = F.read(1)
        if readit == '\t':
            count += 1
    score_string += F.readline()
    print(score_string)

5 个答案:

答案 0 :(得分:2)

这是因为在你的循环中你只在第一行传递了三个标签。您需要继续阅读以阅读所有行。

但你可以用更加pythonic(和更简单)的方式做到这一点:

with open('Program File', 'r') as f: # open file
    for line in f: # get each line
        row = line.split('\t') # split line into in list by tabs
        print row[3] # print fourth value

答案 1 :(得分:1)

您只阅读一行。在文件中的行上使用while循环:

with open('Program File','r') as F:
    for line in F:
        name, surname, age, score=line.split('\t')
        print(score)

答案 2 :(得分:1)

不要尝试在读取文件的同时解析文件,而是首先阅读每一行并在标签上拆分:

with open('Program File') as f:
    for line in f:
        first_name, surname, age, score = line.strip().split('\t')
        print score

答案 3 :(得分:0)

你可以尝试:

with open(filename, 'r') as f:
     data = [l.strip().split('\t') for l in f]

这将提供类似的内容:

data == [["John", "Smith", "17", "22"], ...]

然后,您可以处理data以将最后一个值转换为整数:

scores = [int(l[3]) for l in data]

答案 4 :(得分:0)

您可以使用csv module和字典:

import csv

data={}
with open('/tmp/test.tsv') as f:
    reader=csv.reader(f, delimiter='\t')
    for line in reader:
        data[(line[1], line[0])]=line[2:]

print(data) 
# {('Jones', 'Tom'): ['34', '18'], ('Smith', 'John'): ['17', '22'], ('Martins', 'Lewis'): ['23', '20']}

由于这是一个列表字典,因此访问Tom Jones&#39;年龄你会做data[('Jones', 'Tom')][0]

或者,如果您想要命名值,以便可以像这样访问您的数据:

data[('Martins', 'Lewis')]['score'] 

你可以使用dicts的嵌套词典:

data={}
with open('/tmp/test.tsv') as f:
    reader=csv.reader(f, delimiter='\t')
    for line in reader:
        data[(line[1], line[0])]={'age':line[2], 'score':line[3]} 

# data={('Martins', 'Lewis'): {'age': '23', 'score': '20'}, ('Smith', 'John'): {'age': '17', 'score': '22'}, ('Jones', 'Tom'): {'age': '34', 'score': '18'}}
相关问题