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 txt
file, and then directly read txt
the 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 str
written 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 txt
file in the form of characters, txt
the str
type 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 txt
the str
type data read from the file to the list
data 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 list
object and list
perform str
data type conversion on this object to simulate txt
the data read from the file. From the output of the above code, we can see that the list
type data has been successfully converted to str
type data. Next, we use the ast
module to realize the conversion from str
data type to list
data 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 str
changed 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~