Reading and Writing Text Files

Reading Text Files

  • The readline method returns, as a string, the next line of a text file, including the end-of-line character, \n.
  • When the end-of-file is reached, it returns an empty string.
  • This code will read each line from the file 'myfile.txt' and print it to the console until the end of the file is reached.
  • It is also possible to read the lines of a file by using the for statement. With a for statement, all lines of the file will be read one by one.
 input_file= open('myfile.txt','r')
 for line in input_file:
 print(line)

Using a for statement, all lines of the file will be read one by one. Using a while loop, however, lines can be read until a given value is found.

Writing Text Files

  • The write method is used to write strings to a file.
  • This code copies the contents of the input file, 'myfile.txt', line by line to the output file, 'myfile_copy.txt'.

Finally, when writing to a file, data is first placed in an area of memory called a buffer. Only when the buffer becomes full is the data actually written to the file. Since the last lines written may not completely fill the buffer, the last buffer’s worth of data may not be written. The close() method flushes the buffer to force it to be written to the file.