如何在线长度不同的情况下制作偏移下降线?

时间:2017-05-02 18:25:39

标签: python file offset seek

def load_from_file():
    d = {}  # create empty dict 
    file = open("players.txt", "r")# open file for reading
    line = file.readline()
    file.close()# we’re done with the file
    list = line.split(",")
    prop = {"position":"","number":"","name":"","birth":"","id":""}
    keys = (sorted(prop))
    num = 0
    for key in keys:
        d[key] = list[num]
        num += 1
    return d

问题是每当循环返回到此函数时,它会读取同一行!我希望偏移量下降一个新行

2 个答案:

答案 0 :(得分:0)

问题在于,每次在file.readline()语句中调用函数时,您都告诉程序只读取文件的第一行。您应该立即将所有文件读入列表,然后遍历已读入列表的行。

示例:

def load_from_file():
    with open("players.txt", "r") as myfile # open file for reading
       myfile = file.readlines()
    return myfile

def create_dictionary(line):
    d = {}
    list = line.split(",")
    prop = {"position":"","number":"","name":"","birth":"","id":""}
    keys = (sorted(prop))
    num = 0
    for key in keys:
       d[key] = list[num]
       num += 1
    return d

data = []
filedata = load_from_file()
for line in filedata:
    data.append(create_dictionary(line))

P.S。不确定你要对数据做什么,但这应该有助于你获得要点。

答案 1 :(得分:0)

使用DictReader模块中的csv

def load_from_file():
    with open("players.txt") as players:
        fields = ["birth", "id", "name", "number", "position"]
        reader = csv.DictReader(players, fields)
        return list(reader)