Python txt file read data type str converted to list type

When we want to write our own small programs, such as the check-in applet (click on the hyperlink to jump), we need to save some simple data. At this time, if we go to study the database, such as SQL, MySQL is superfluous and the most practical. The strategy is that we directly save the data results obtained after running in a txtfile, and then directly read txtthe data in the file for operation when the program is called next time . But in this process we will encounter a serious problem, that is txt, the data we write to the file is usually strwritten in the form of characters, and when it is read, it is also read in the form of characters, that is, if we After writing a list of data into a txtfile in the form of characters, txtthe strtype of the data read from the file next time becomes the type, which makes it impossible to perform the operations we need. At this time, it will be very tricky. For this, we will introduce one A method that can convert txtthe strtype data read from the file to the listdata type.
code show as below:

class Debug:
    def mainProgram(self):
        list1 = [[2, 0], [4, 0]]
        print(type(list1))  # <class 'list'>
        print(list1)        # [[2, 0], [4, 0]]
        list1 = str(list1)
        print(type(list1))  # <class 'str'>
        print(list1)        # [[2, 0], [4, 0]]


if __name__ == "__main__":
    main = Debug()
    main.mainProgram()

We first create an listobject and listperform strdata type conversion on this object to simulate txtthe data read from the file. From the output of the above code, we can see that the listtype data has been successfully converted to strtype data. Next, we use the astmodule to realize the conversion from strdata type to listdata type. code show as below:

import ast


class Debug:
    def mainProgram(self):
        list1 = [[2, 0], [4, 0]]

        list1 = str(list1)
        
        list1 = ast.literal_eval(list1)
        print(list1)        # [[2, 0], [4, 0]]
        print(type(list1))  # <class 'list'>


if __name__ == "__main__":
    main = Debug()
    main.mainProgram()

We can see that the data type obtained has strchanged from a type that can be operated on list.
If you find it useful, please raise your hand to give a like and let me recommend it for more people to see~

Guess you like

Origin blog.csdn.net/u011699626/article/details/108674438