Python read file into multiple lists
Ngày đăng:
24/01/2022
Trả lời:
0
Lượt xem:
156
In todays tutorial well learn to import Python lists into files. Well cover three main use cases: Show
Save list to a new text / csv fileWell start by creating the new file using the file open method, then loop through the list and write the list elements each in a different line. Append Python list to text / csv fileIn this example, well first check whether our file exists in the operating system, and then append the list values to the file. Heres the code to use: Write multiple lists to a file with PythonWe would like now to import multiple lists into the file. One list has offices and the second has the corresponding number of employees. offices = ['Atlanta', 'Boston', 'New York', 'Miami'] employees = [100,120,140,150]Well now use the zip function to stitch the two lists, and then import them as needed into the a csv file. Heres the output: Export list of dictionaries to a fileWell use the json module to transfer the dictionary list. dict1 = dict (Atlanta = 100, Boston = 120) dict2 = dict(NewYork = 140, Miami=150) my_dicts = [dict1, dict2] import json with open('my_dict.txt', 'w') as my_file: json.dump(my_dicts, my_file) |