如何打开文件并将项目附加到Python中的现有列表

时间:2018-08-07 03:26:42

标签: python append

我是编码和堆栈溢出的新手。我搜索了该网站,但找不到我想要的东西。

我试图打开一个文件,然后将一个项目附加到该文件中的现有列表中。但是,似乎只想将项目添加到列表中的现有字符串中。因此,列表停留在一项,并且字符串仅在继续增长。

到目前为止,这是我的代码:     导入数学     进口统计

def differential(score,course_rating,slope_rating):
    diff = (score - course_rating) * 113 / slope_rating
    return math.floor(diff*100)/100

def data_gather():
    score = int(input("Enter your score: "))
    course = float(input("Enter the course rating: "))
    slope = int(input("Enter the slope rating: "))
    return differential(score,course,slope)

with open("handicap.txt", "a+") as hc:
    hc.write("[],"
             .format(data_gather()))

scores = []

with open("handicap.txt", "r") as hc:
    scores.append(hc.read())`

每次运行此代码时,我都希望将用户输入的最终结果(即函数)添加到列表中。最好是整数,但是如果是字符串,我可以在以后解决,我只需要将每个项目都设为自己的项目即可,而不是添加到一个大字符串上。

非常感谢大家!

3 个答案:

答案 0 :(得分:0)

只需添加换行符(\n):

with open("handicap.txt", "a+") as hc:
    hc.write("[],\n"
             .format(data_gather()))

答案 1 :(得分:0)

with open("handicap.txt", "a+") as hc:
hc.write("[],"
         .format(data_gather()))

不确定您要在这里完成什么。要使用format。您需要使用{}

要修改您的代码,请执行以下操作:

import math 
import statistics

def differential(score,course_rating,slope_rating):
    diff = (score - course_rating) * 113 / slope_rating
    return math.floor(diff*100)/100

def data_gather():
    score = int(input("Enter your score: "))
    course = float(input("Enter the course rating: "))
    slope = int(input("Enter the slope rating: "))
    return differential(score,course,slope)

with open("handicap.txt", "a+") as hc:
    hc.write("{}\n"
             .format(data_gather()))

scores = []

with open("handicap.txt", "r") as hc:
    scores = [float(_) for _ in hc.read().split('\n')[:-1]] 

代码的最后一行是取出最后一个元素(为空,因为我们每次都添加一个\ n字符),然后转换为浮点数。

答案 2 :(得分:0)

如果使用Pickle,则可以避免编写字符串。

import cPickle

mylist = [1,2,3,'test','string']
with open('myfile.pkl', 'wb') as f:
    cPickle.dump(mylist, f, cPickle.HIGHEST_PROTOCOL)

要读取并附加到文件,请执行

item_to_append = 'append_string'
with open('myfile.pkl', 'rb+') as f:
    mylist = cPickle.load(f)
    mylist.append(item_to_append)
    f.seek(0)
    cPickle.dump(mylist, f, cPickle.HIGHEST_PROTOCOL)

如果要查看结果,请打开并阅读文件:

with open('myfile.pkl', 'rb') as f:
    saved_list = cPickle.load(f)
    print(saved_list)

> [1, 2, 3, 'test', 'string', 'append_string']