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.