In Python we can write to a text file by using Python code to open and write the file. Today’s lesson comes with some help from a few WWF stars.
Opening a file is easy in Python.
The open function will open a file or create one if it doesn’t exist in the place you save the Python script.
The code below shows you how to refer to a file name in a variable.
x = open("filename.txt", "w")
We can then add text by using the write function with the file variable. (The “w” part)
You must always close a file when finished.
file = open('filename.txt', 'w') # This line opens a text file for writing (w). file.write('Ted Dibiase') # The previous line created a variables to open a file. This line refers to opening a file and writing a line inside it. file.write('Terry Bollea') # What does this line do? file.close() # This line closes the file that was opened.
Task 1 Now it’s your turn. in the Python window below type some code so that some names are added to the text file. Add 5 wrestler names using a new line for each name. If you dont know any wrestler names list 5 Michael Jackson songs, 5 Beatles songs or if you are a complete loser, names reality TV shows.
Does a text file appear in the Python interpreter window? Check if the names appear in the text file.