【问题标题】:how to make the offset drop line while the lines aren't the same length?如何在线条长度不同时制作偏移下降线?
【发布时间】:2017-05-02 18:25:38
【问题描述】:
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

问题在于,每当循环返回到这个函数时,它都会读取同一行!我希望偏移量删除一个新行

【问题讨论】:

  • 什么是“偏移量”
  • 你读了一行,然后关闭文件。从文件as the documentation says 中读取每一行,然后用它做你想做的事。
  • 你能告诉我怎么做吗?
  • 这不是一个真正的教程网站。有足够的文档。如果遇到困难,请尝试一些问题并提出问题。
  • 看看csv,尤其是DictReader

标签: python file offset seek


【解决方案1】:

问题是你告诉程序每次在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))

附:不确定您要对数据做什么,但这应该可以帮助您了解要点。

【讨论】:

  • @Peter Wood,没有必要,但不太复杂,特别是他每次在函数中打开文件的方式。更容易对 Python 列表进行操作,而不是处理文件指针。
  • for line in myfile 并不复杂
【解决方案2】:

使用来自csv 模块的DictReader

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

【讨论】:

    猜你喜欢
    • 2019-10-01
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多