简体   繁体   中英

Python does not reads a fetched line from text file as in Dictionary format

I've a text input file with different inputs as below stored in dictionary and list format respectively. A portion of the text file is below:

#Drive-Size-Mapping
{'root' : 50 , '\usr' : 20, 'swap' : 1}
#OS-Version
[7.1, 7.2, 7.3, 7.4, 7.5, 7.6]

As you can see the first line is in Dictionary format and the 2nd line is in List format. Now, when I'm reading and storing the lines in variables, Python fails to recognize the format. This is my code I'm trying:

 f=open("C:\\Users\xyz\\Desktop\\Inputs.txt")
lines=f.readlines()
i = lines.index("#Drive-Size-Mapping\n")
di=dict()
di = lines[i+1]
print(di[0])
j = lines.index("#OS-Version\n")
list = lines[j+1]
print(list[0])

The out of above code is:

{ {

ie it just prints the item which is present in the first array index of the array. What I want python to interpret these variables as dictionary and List respectively. So , if I do print di["root"]

My code should recognize it as dictionary and print as 50 . And print(list[0]) should recognize it as list and output 7.1.

Please let me know how should the file lines be manipulated so as to make python interpret them in the format they are actually present?

Thank You

Just adding to the above answers:

Use:

 ast.literal_eval()

But remove/replace "\\" from the keys of the dictionary as it can create unicode error in literal_eval() function

One more error in the code, after converting to dictionary, you cannot do d[0] as dictionaries are not indexed

The function readlines does what it says: it reads lines . You and I can recognize that the two lines are a Python dict and a Python list, but Python cannot and also should not.

It seems to me that you are reading configuration settings in from a file with Python source in it. A more standard way to do that is to use an .ini file. Look at the module configparser .

The lines you are getting from the file are string . If you want to convert them to dict or list objects, you can use literal_eval :

from ast import literal_eval

...
d = literal_eval(lines[i+1])
...
l = literal_eval(lines[i+1])

If you can change the format of the input file, I would look into modifying it to a json file to store and load your objects conveniently with the json module .

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