简体   繁体   中英

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. What is the mistake in saving the file?

Update:

the 'a' array is having strings on different lengths. 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 ?

You can save the list directly on file and use the eval function to translate the saved data on file in list again. 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. Whereas data is a list with three strings. readfile.readlines() or list(readfile) writes all lines in a list. So, when you perform data = readfile.readlines() python consider ['str1','str2','str3']\\n as a single string and not as a list. So,to get your desired output you can use following print statement. print(data[0][2:6])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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