0

I have an old file written using python2, which contains things like 148191387849281587952L. When I try to read it (using ast.literal_eval) in python3, I, naturally, get SyntaxError: invalid syntax.

Is there anything I could do to read the file into python3?

PS. The only solutions I see at this time require modifying the file:

  1. Convert to JSON: read the file into python2, write it using json, then read into python3 using json.

  2. Remove the offending L using sed -i 's/([0-9]+)L/\1/g'.

  3. Convert the file using 2to3 (suggested by @user3080953).

Is there anything better?

sds
  • 58,617
  • 29
  • 161
  • 278
  • I like the idea of using a version-agnostic serialization approach, such as JSON, but I think your solution #1 seems a little roundabout. It sounds like your idea is "write the file using python2, then read it in python2, then write it with json, then read it in python 3 using json", it seems like it would be easier to modify your original program so it writes json in the first place. That'll save you two steps. – Kevin Jul 31 '18 at 15:35
  • 2
    You shouldn't have a file with python object representations in first place - they are not a reliable storage method! – nosklo Jul 31 '18 at 15:35
  • @Kevin: I have a bunch of old files written by python2, and I need to read them into python3 – sds Jul 31 '18 at 15:36
  • @nosklo: [JSON takes up too much screen real estate](https://stackoverflow.com/q/45681702/850781) ;-) but you are right, JSON is, alas, the way to go... – sds Jul 31 '18 at 15:38
  • @sds time to put those ultrawide monitors to use – nosklo Jul 31 '18 at 15:39
  • @nosklo: the problem is that JSON is either "horizontal" (`ident=None`, no structure, virtually unreadable) or "vertical" (`ident!=None`, one object per line, many many many lines per record). – sds Jul 31 '18 at 15:43
  • @sds I was joking - json is not for humans to read. Make a gui program to read your data and display to the user as a nicely formatted report, with graphics. – nosklo Jul 31 '18 at 15:44
  • Would running 2to3 on the file fix it? It seems like a simple case that should be handled by that – c2huc2hu Jul 31 '18 at 16:15
  • @user3080953: yes! thanks! this is a 3rd solution I want to avoid :-) – sds Jul 31 '18 at 16:17
  • It looks like you are trying to avoid solutions instead of fixing the problem. Here's another one: read it in Python2 and write new files in JSON or some other common format. – Elazar Jul 31 '18 at 16:23
  • @Elazar: that's the solution #1 on my list. My question is: can I modify Python3 syntax to read `L`. – sds Jul 31 '18 at 16:26

1 Answers1

0

After your clarification, there is a simple answer:

No, you cannot modify ast.leteral_eval() or the python interpreter to be "backwards compatible" with the L syntax.

Elazar
  • 20,415
  • 4
  • 46
  • 67
  • (Nor would I consider it to be a good idea, changing the interpreter in order to read external data) – Elazar Jul 31 '18 at 17:20