Writing data to a text file

The file.write() command only takes a single parameter – this is best achieved using an f-string.

End-of-line characters “\” should also be written.

Writing lines of text

Opening a file with “w” parameter will create a new file, or overwrite any existing file.

Opening a file with “a” parameter will create a new file, or append to any existing file.

#
OUT_FILE= 'results.txt'
 
def writeDataToFile(data):
    f = open(OUT_FILE, 'a')
    f.write(f"{data}\n")
    f.close()
    print("data written")

#MAIN PROGRAM
writeDataToFile("fred")
writeDataToFile("alice")
writeDataToFile("sue")

Writing arrays

OUT_FILE= 'results.txt'

def writeDataToFile(names, marks):
    with open(OUT_FILE, 'w') as f:
        for student in range(len(marks)):
            f.write(f"{names[student]},{marks[student]}\n")
    print(f"Data written to {OUT_FILE}")

#MAIN PROGRAM
#
writeDataToFile(names, marks)
#

Writing records

OUT_FILE= 'results.txt'

def writeDataToFile(students):
    with open(OUT_FILE, 'w') as f:
        for student in students:
            f.write(f"{student.name},{student.mark}\n")
    print(f"Data written to {OUT_FILE}")

#MAIN PROGRAM
#
writeDataToFile(students)
#