[英]issue in saving string list in to text file
我正在尝试保存和读取保存在文本文件中的字符串。
a = [['str1','str2','str3'],['str4','str5','str6'],['str7','str8','str9']]
file = 'D:\\Trails\\test.txt'
# writing list to txt file
thefile = open(file,'w')
for item in a:
thefile.write("%s\n" % item)
thefile.close()
#reading list from txt file
readfile = open(file,'r')
data = readfile.readlines()#
print(a[0][0])
print(data[0][1]) # display data read
输出:
str1
'
a [0] [0]和data [0] [0]都应具有相同的值,我保存的读数将为空。 保存文件有什么错误?
更新:
'a'数组具有不同长度的字符串。 保存文件时可以进行哪些更改,以便输出相同。
更新:
我已通过使用此链接将文件保存在csv中而不是文本中进行了更改,以防万一文本如何保存数据?
您可以将列表直接保存在文件中,然后使用eval函数再次将保存的数据转换为列表中的文件。 不推荐使用,但是以下代码可以正常工作。
a = [['str1','str2','str3'],['str4','str5','str6'],['str7','str8','str9']]
file = 'test.txt'
# writing list to txt file
thefile = open(file,'w')
thefile.write("%s" % a)
thefile.close()
#reading list from txt file
readfile = open(file,'r')
data = eval(readfile.readline())
print(data)
print(a[0][0])
print(data[0][1]) # display data read
print(a)
print(data)
a和data的值将不等于a是三个列表的列表。 而data是包含三个字符串的列表。 readfile.readlines()
或list(readfile)
将列表中的所有行写入。 因此,当您执行data = readfile.readlines()
python时,请将['str1','str2','str3']\\n
视为单个字符串而不是列表。 因此,要获得所需的输出,可以使用以下打印语句。 print(data[0][2:6])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.