Python read file into multiple lists

In todays tutorial well learn to import Python lists into files. Well cover three main use cases:

  • Import list into a new file (could be txt, csv, json or others).
  • Append a list to an existing file.
  • Write multiple lists to a file
  • Write a list of dictionaries to a file
offices = ['Atlanta', 'Boston', 'New York', 'Miami']

Save list to a new text / csv file

Well 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.

with open('my_file.csv', 'w') as my_file: my_file.write('Office branches:' + '\n') for branch in offices: my_file.write(branch + '\n') print('File created')

Append Python list to text / csv file

In 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:

from pathlib import Path my_file = Path('C:\Temp\my_file.xlsx') # check if directory exists if my_file.is_file(): with open (my_file, 'a') as my_file: my_file.write('\n'+ 'Office branches:' + '\n') for o in offices: my_file.write(o + '\n') print('File updated') else: print('File not available')

Write multiple lists to a file with Python

We 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.

office_emps = zip(offices, employees) with open('my_file.csv', 'w') as my_file: for (offices,employees) in office_emps: my_file.write("{0},{1}\n".format(offices,employees)) print('File created')

Heres the output:

Python read file into multiple lists

Export list of dictionaries to a file

Well 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)