说我有这个清单:
SOME_LIST = []
随着程序的继续,其中的数据来自用户输入。
所以程序运行后最终会像:
SOME_LIST = [1, 2, 3, 5, 4]
如何将some_list
保存到CSV文件中,以便在程序关闭时,可以在程序再次运行时加载CSV文件,some_list
将再次包含其中的所有元素
我的尝试:
import csv
import os.path
def main():
SOME_LIST = []
for i in range(1 , 6):
SOME_LIST.append(int(input('Enter an integer')))
print ('Press 1 to save your list')
print ('Press 2 to load your previous list')
user_answer = int(input('Enter your selection now'))
if user_answer == 1:
saved_file = open('My destination folder')
writer = csv.writer(saved_file, dialect='excel')
writer.writerow(SOME_LIST)
if user_answer == 2:
'''However you can load the csv file and update some_list with \
the files contents'''
main()
我只是得到一个unicode错误,说它无法读取2-3位的字节
尝试#2
def main():
SOME_LIST = []
for i in range(1 , 6):
SOME_LIST.append(int(input('Enter an integer')))
print ('Press 1 to save your list')
print ('Press 2 to load your previous list')
user_answer = int(input('Enter your selection now'))
if user_answer == 1:
saved_file = open('My destination folder')
f.write((",".join(SOME_LIST))
f.close
if user_answer == 2:
'''However you can load the csv file and update some_list with \
the files contents'''
main()
答案 0 :(得分:0)
为什么要导入csv
模块?据我所知,csv
文件只是一个常规文本文件,其值以逗号分隔,因此
"逗号分隔值"
您只想存储单个列表这一事实使得为此导入单独的模块毫无用处。
最好的选择是使用字符串对象的join()
和split()
方法。
如何保存文件:
print(",".join(SOME_LIST))
第一个字符串","
是分隔符,参数是用逗号分隔的列表。
如何加载文件:
SOME_LIST=(file.read().split(",")
这将使用逗号读取文件,并用逗号分隔,将结果保存在SOME_LIST
变量中。
答案 1 :(得分:0)
这里有一个可以保存列表并加载它的工作版本:
def main():
SOME_LIST = []
for i in range(1 , 6):
SOME_LIST.append(int(input('Enter an integer')))
print ('Press 1 to save your list')
print ('Press 2 to load your previous list')
user_answer = int(input('Enter your selection now'))
if user_answer == 1:
f = open('2.txt','w')
list=[str(i) for i in SOME_LIST]
f.write((",".join(list)))
f.close()
if user_answer == 2:
f = open('2.txt','r')
aux=f.read()
list=aux.split(",")
print (list)
f.close()
main()的
答案 2 :(得分:0)
我尽可能少地修改了你的代码。基本上你需要在写模式下打开文件来编写csv文件。此外,您必须指定扩展名(在这种情况下,您正在写入csv,因此它将是.csv,但还有其他选项,如.txt)。要阅读文件,您可以使用csv阅读器,我举了一个如何做到这一点的例子。我也在下面的代码中添加了一些注释。
import csv
import os.path
def main():
SOME_LIST = []
for i in range(1 , 6):
SOME_LIST.append(int(input('Enter an integer')))
print ('Press 1 to save your list')
print ('Press 2 to load your previous list')
user_answer = int(input('Enter your selection now'))
if user_answer == 1:
#Notice the w in the line below and the .csv, these both must be specified
# if you want to write a csv file!
saved_file = open('My destination folder.csv','w')
writer = csv.writer(saved_file, dialect='excel')
writer.writerow(SOME_LIST)
if user_answer == 2:
#Open the file, be sure to include the entire path to the file you wish
# to open!
file = open('path to my destination folder/My destination folder.csv','r')
rd = csv.reader(file)
l = list(rd)[0] #Note make sure to put this [0] at the end!
l2 = []
for j in range(5):
num = l[j]
l2.append(int(num))
print(l2)
main()