Writing Text Files

Methods of writing a text file

.write()

.writelines()

.write()

.write() is a method of a file object. The file object is created by the open() statement.

When the .write()method is called, the contents of the string variable is written to the file.

.write() Syntax

Note: To write() to a file, the file first must be opened.

file_object.write(string_variable)

string_variable: a variable (or literal) that contains a string

file_object: the name that will be used in the program to process the file.

.write () Examples

Write keyboard input to a file. Stop input when no data is entered.

def writef(fname ='outfile.txt'):

f = open(fname, 'w')

line = input('Enter some data for a line: ')

while line != '':

f.write(line+ '\n')

line = input('Enter some data for a line: ')

f.close()

.writelines()

.writelines() Syntax

Note: To writeline() to a file, the file first must be opened.

file_object.writeline(string_variable)

string_variable: a variable (or literal) that contains a string

file_object: the name that will be used in the program to process the file.