-1

Okay so I have this list of tuples:

[(0, 'Paper 1.jpg'), (1, 'Paper 2.jpg'), (2, 'Paper  3.jpg'), (0, 'Paper 4.jpg'), (1, 'Paper 5.jpg'), (2, 'Paper 6.jpg'), (0, 'Paper 7.jpg'), (1, 'Paper 8.jpg')]

And basically I just want to save this list either to a .txt file or a .json file and read it elsewhere.

The problem is that when I save it as a .txt file; when I try to read it, Python takes this as a string. And I can't convert this string of list of tuples to its original state.

Or when I write this to a .json file, JSON doesn't know what a tuple is and saves all the tuples in the list as a list, so I got a nested list which ruins the whole purpose.

Can anybody help me on this?

I've never worked with .xml file, maybe I should save this list in an .xml file?

knayman
  • 77
  • 6

4 Answers4

1

Have you considered just calling eval on the string you get with method 1?

Igor Rivin
  • 3,463
  • 1
  • 15
  • 19
1

You can use json.dump to properly load your list into a json object and then write it to a file (see json module documentation).

Herr Flick
  • 52
  • 8
1

Use JSON all the way:

import json

lst = [(0, 'Paper 1.jpg'), (1, 'Paper 2.jpg'), (2, 'Paper  3.jpg'), (0, 'Paper 4.jpg'), (1, 'Paper 5.jpg'),
       (2, 'Paper 6.jpg'), (0, 'Paper 7.jpg'), (1, 'Paper 8.jpg')]

# save as json
with open('data.json', 'w') as f:
    json.dump(lst,f)

# read the file
with open('data.json') as f:
   lst1 = [tuple(x) for x in json.load(f)]
   print(f'lst1: {lst1}')

output

lst1: [(0, 'Paper 1.jpg'), (1, 'Paper 2.jpg'), (2, 'Paper  3.jpg'), (0, 'Paper 4.jpg'), (1, 'Paper 5.jpg'), (2, 'Paper 6.jpg'), (0, 'Paper 7.jpg'), (1, 'Paper 8.jpg')]
balderman
  • 12,419
  • 3
  • 21
  • 36
0

Fortunately, there's an alternative to JSON: PyYAML! It has the ability to store data types present only in Python--including tuples. (The full documentation for PyYAML is here.)

Stringifying a list of tuples:

import pyyaml
x = [(1, 2), (2, 3)]
print(yaml.dump(x))

will produce the following:

- !!python/tuple
  - 1
  - 2
 -!!python/tuple
  - 2
  - 3

And if you want to convert a YAML string into a Python object, use yaml.load():

x = """
- !!python/tuple
  - 1
  - 2
-!!python/tuple
  - 2
  - 3
"""
print(yaml.load(x))

will produce [(1, 2), (2, 3)].