How do i write to a file in python?
-
Here we create simple list, tell python what our file name and mode is, here the mode is "w" is used to write, then we loop over the list.
Functions used is the open function to open a file, the write function to write to a file, the close function to close a file, this is straightforward.
my_cakes = ["fruit", "ginger", "lemon"] cake_shopping_list = open("cakestobuy.txt", "w") for item in my_cakes: cake_shopping_list.write(item + "\n") cake_shopping_list.close()
The pathname of the file is the current directory and the put is:
$ cat cakestobuy.txt fruit ginger lemon
© Lightnetics 2024