简体   繁体   中英

Saving an nested list into a text file

Problem 1: I want to create a program that gathers the Name, Age and Year Group from a person. I then want to save this into a nested loop.

AD = [["Name","Age","Year"],["Mark","15","11"]]

Inp = input("Name:")
AD.append(Inp)

Inp = input("Age:")
AD.append(Inp)

Inp = input("Year:") 
AD.append(Inp)

print(AD)

So I tried this...

Name:Jack
Age:14
Year:10
[['Name', 'Age', 'Year'], ['Mark', '15', '11'], 'Jack', '14', '10']
>>> 

I want the result to look like...

Name:Jack
Age:14
Year:10
[['Name', 'Age', 'Year'], ['Mark', '15', '11'], ['Jack', '14', '10']]
>>> 

Problem 2: I wish to then save and read from a File.

AD = [["Name","Age","Year"],["Mark","15","11"]]

Inp = input("Name:")
AD.append(Inp)

Inp = input("Age:")
AD.append(Inp)

Inp = input("Year:")
AD.append(Inp)

File = open("Details.txt","w")
File.write(AD)
File.close()

print(AD)

It then comes up with the problem of "write()" only using strings. How can easily save this information so when I'm given a name I can use it to find the 2 numbers related to it?

Thanks <3

Problem 1:

AD = [["Name","Age","Year"],["Mark","15","11"]]

name = input("Name:")
age = input("Age:")
year = input("Year:") 

AD.append([name, age, year])
print(AD)

Problem 2:

writing

with open('Details.txt','w') as f:
    f.write('\n'.join([','.join(person) for person in AD]))

reading

with open('Details.txt', 'r') as f:
   lines = f.readlines()
   AD = {}
   for line in list(lines)[1:]:
       name, age, year = line.split(',')
       AD[name] = [age, year]

name = input('Wich person do you want to squery? ')
age, year = AD[name]
print('This person has age {0} and year {1}'.format(age, year))

If you don't mind to save as a CSV file, then you can create a Panda data frame with 3 columns using these lists and then save as a CSV file. Later you can read the CSV file and fetch the values of "Age" and "Year" columns based on the value in "Name" column

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