简体   繁体   中英

Writing list of lists in float format from python to text file

I have a list of lists which I want to write to a text file. Then, I have to read that text file, edit that list of lists and again write it back to the text file.

Now, I am not able to write it without string format. So, when I read it, I can not make the required changes because it becomes a string.

For my case, list of lists looks like

A = [[0,[0.0,1010.0,10.0],[10.0,1110.0,10.0]],[0,[10.0,1011.0,15.0],[15.0,1111.0,19.0]]]

I didn't find any solution for this problem. Any help is highly appreciated.

Note: When I read A and try converting it to float, it was trying to convert [ into float. Hence, it didn't work.

You should dump into the file as-is, there's many ways of doing this, one way will be to use json .

import json
A=[[0,[0.0,1010.0,10.0],[10.0,1110.0,10.0]],[0,[10.0,1011.0,15.0],[15.0,1111.0,19.0]]]
json.dump(A, open("file.txt","w")) # your file path

To load it you can do:

json.load(open("file.txt"))

Another way is the dump the file as a string of the list and retrieve it using ast.literal_eval as suggested by Jean-François.

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