banner

© 2004-19 ict4u.net

Python File Handling

Being able to read and write text and csv files with Python is a useful programming skill and often required in Project Work or Practical Exams.

To read the data in a file, it has to be opened the variable used to open the file acts as a file handler which looks after reading and writing data

One of the most important things it know about when reading a file is which is the next record (if there is one) to be read.

This diagram shows the file pointer advancing after each record is read until it reaches the End Of File (EOF) marker, which indicates there is no more data.
To reset the file pointer, the file has to be closed and re‐opened.

Method Description
Read TXT by line data Read data from a text file line by line
Read TXT data Read data from a text file
Write TXT data Write data to a text file and add newline characters