© 2004-19

Writing a Text File

Text files are very easy to create with Python
  1. open the file and assign a file handler,
  2. use the write method to save the data (remember to add a newline character)
  3. NOTE: the file will bre created in the current working directory and overwrite an existing file of the same name
# Author: A Knifton
# Date: 6 Dec 2017
# Purpose:Write  simple text file

fileName = "Students.txt"
myFile = open(fileName, "w")  # open the file for writing

myFile.write('Amos Kelly\n')  # write each line individually
myFile.write('Darla Lloyd\n')  # remember to add the newline character!
myFile.write('Brett Haynes\n')
myFile.write('Eric Stanley\n')
myFile.write('Victor Garza\n')
myFile.write('Kate Estrada\n')
myFile.write('Judy Walsh\n')
myFile.write('Dennis Morrison\n')

# now close the file

# read the data back
myFile = open(fileName, "r")
textList = myFile.readlines()
print(f"The file :{fileName}\nContains: {textList}")