How to Output a List to a Text File?

python
1wcuResidenceHalls = ['walker', 'scott', 'harrill']
2
3def saveFile():
4    f = open("WCU_Residence_Halls.txt", "a")
5    for wcuResidenceHall in wcuResidenceHalls:
6        f.write(wcuResidenceHall + "\n")
7    f.close()
8
9saveFile()
  • On the first line in the saveFile function body, weโ€™re opening a file called WCU_Residence_Halls.txt. This is the first argument to the Pythonโ€™s built-in open function
  • This file does not have to exist because we have this โ€˜aโ€™ as the second argument. The โ€˜aโ€™ denotes that we want to append some text to this file. โ€œfโ€ represents the object (i.e., the file) in memory.
  • On the third line in the function body, we are actually writing to our file. We use the write function, which takes a string and writes it to a file
  • Finally on the fourth line we close the file
  • We call the saveFile function at the end.