简体   繁体   English

将字符串列表保存到文本文件中的问题

[英]issue in saving string list in to text file

I am trying to save and read the strings which are saved in a 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

the output: 输出:

str1
'

both a[0][0] and data[0][0] should have the same value, reading which i saved returns empty. a [0] [0]和data [0] [0]都应具有相同的值,我保存的读数将为空。 What is the mistake in saving the file? 保存文件有什么错误?

Update: 更新:

the 'a' array is having strings on different lengths. 'a'数组具有不同长度的字符串。 what are changes that I can make in saving the file, so that output will be the same. 保存文件时可以进行哪些更改,以便输出相同。

Update: 更新:

I have made changes by saving the file in csv instead of text using this link , incase of text how to save the data ? 我已通过使用此链接将文件保存在csv中而不是文本中进行了更改,以防万一文本如何保存数据?

You can save the list directly on file and use the eval function to translate the saved data on file in list again. 您可以将列表直接保存在文件中,然后使用eval函数再次将保存的数据转换为列表中的文件。 Isn't recommendable but, the follow code works. 不推荐使用,但是以下代码可以正常工作。

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 and data will not have same value as a is a list of three lists. a和data的值将不等于a是三个列表的列表。 Whereas data is a list with three strings. 而data是包含三个字符串的列表。 readfile.readlines() or list(readfile) writes all lines in a list. readfile.readlines()list(readfile)将列表中的所有行写入。 So, when you perform data = readfile.readlines() python consider ['str1','str2','str3']\\n as a single string and not as a list. 因此,当您执行data = readfile.readlines() python时,请将['str1','str2','str3']\\n视为单个字符串而不是列表。 So,to get your desired output you can use following print statement. 因此,要获得所需的输出,可以使用以下打印语句。 print(data[0][2:6])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM