Text Files

A text file is a file containing characters, structured as individual lines of text.

  • In addition to printable characters, text files also contain the non-printing newline character, \n, to denote the end of each text line.
  • The newline character causes the screen cursor to move to the beginning of the next screen line.
  • Thus, text files can be directly viewed and created using a text editor.

In contrast, binary files can contain various types of data, such as numerical values, and are therefore not structured as lines of text. Such files can only be read and written via a computer program. Attempting to directly view a binary file will result in "garbled" characters on the screen.

Using Text Files

Opening Text Files

To use a file in Python, it must first be opened. Opening a file creates a file object that provides methods for accessing the file. Files can be opened for either reading or writing.

Opening for Reading

  • To open a file for reading, the open() function is used with the file name and mode 'r' (indicating read mode).
  • If the file is successfully opened, a file object is created and assigned to the provided identifier in this case identifier input_file.
  • However, if the file does not exist or cannot be found, an I/O error will occur.

When a file is opened, it is first searched for in the same folder/directory that the program resides in. However, an alternate location can be specified in the call to open by providing a path to the file:

input_file = open('data/myfile.txt', 'r') 

In this case, the file is searched for in a subdirectory called data of the directory in which the program is contained.

Absolute paths can also be provided, giving the location of a file anywhere in the file system:

input_file = open('C:/mypythonfiles/data/myfile.txt', 'r')

When the program has finished reading the file, it should be closed by calling the close method on the file object:

input_file.close()

Once closed, the file may be reopened (with reading starting at the beginning of the file) by the same or another program.

Opening for Writing

To open a file for writing, the open() function is used with the file name and mode 'w' (indicating write mode).

If the file already exists, it will be overwritten. If the file does not exist, a new file will be created.

When using a second argument of 'a', the output will be appended to an existing file instead.

It's important to close the file after writing to ensure all data is properly saved.