相关疑难解决方法(0)

使用Python将列表写入文件

这是将列表写入文件的最简洁方法,因为writelines()不插入换行符吗?

file.writelines(["%s\n" % item  for item in list])
Run Code Online (Sandbox Code Playgroud)

似乎有一种标准方式......

python file-io newline file list

601
推荐指数
16
解决办法
142万
查看次数

如何将列表保存到文件并将其作为列表类型读取?

假设我有列表得分= [1,2,3,4,5],并且在我的程序运行时它会被更改.如何将其保存到文件中以便下次运行程序时我可以将更改后的列表作为列表类型进行访问?

我试过了:

score=[1,2,3,4,5]

with open("file.txt", 'w') as f:
    for s in score:
        f.write(str(s) + '\n')

with open("file.txt", 'r') as f:
    score = [line.rstrip('\n') for line in f]


print(score)
Run Code Online (Sandbox Code Playgroud)

但这会导致列表中的元素不是整数.

python file list pickle python-3.x

27
推荐指数
7
解决办法
10万
查看次数

标签 统计

file ×2

list ×2

python ×2

file-io ×1

newline ×1

pickle ×1

python-3.x ×1