0

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 ?

Raady
  • 1,686
  • 5
  • 22
  • 46

2 Answers2

1

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)
  • It is giving an error when adding eval. "TypeError: eval() arg 1 must be a string, bytes or code object" – Raady Apr 02 '18 at 14:40
  • Check if this line `data = eval(readfile.readline())` is `readline()` not `readlines()` – Mateus Milanez Apr 02 '18 at 16:39
  • eval not working. I am using python 3.6 does that making any difference? – Raady Apr 03 '18 at 10:00
  • @Raady I tested it with python 3.6.4 and 2.7.14 and the result are the same. `python2 bla.py [['str1', 'str2', 'str3'], ['str4', 'str5', 'str6'], ['str7', 'str8', 'str9']] str1 str2`. `python3 python bla.py [['str1', 'str2', 'str3'], ['str4', 'str5', 'str6'], ['str7', 'str8', 'str9']] str1 str2` – Mateus Milanez Apr 03 '18 at 12:40
0

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])

nsr
  • 855
  • 7
  • 10
  • This is an example, str1 and str2 in my data are not of same size. In that case how can I save the data so that the output will be same ? or else is there any other read function ? – Raady Apr 02 '18 at 12:32