1. Text files

Download the test csv file 12days.txt

1.1. Reading files

The code below opens a file for reading, reads the file, prints the file contents, then closes the file.
f is commonly used to refer to the file object from opening a file.
filepath = "files/12days.txt"
f = open(filepath, "r")
print(f.read())
f.close()
The syntax used in each line of the code above is described below.

1.1.1. Open file:

Use the open() function to open a file.
The most used syntax is:
open(file, mode='r')
Parameters:
  • file – a string for the file path to the file from the current directory.

  • mode – a string; “r” to read; “w” to write; “a” to append; “r+” to read and write; “b” for binary; “t” for text. Defaults are “rt” for read text.

Open file and return a corresponding file object.
The recommended syntax is:
open(file, mode='r', encoding='utf-8')
The full Syntax for advanced use:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Parameters:
  • file – a string for the file path to the file from the current directory.

  • mode – a string; “r” to read; “w” to write; “a” to append; “r+” to read and write; “b” for binary; “t” for text. Defaults are “rt” for read text.

  • buffering – an optional integer used to set the buffering policy.

  • encoding – defaults to system; “utf-8” is recommended; see: https://docs.python.org/3/library/codecs.html#standard-encodings

  • errors – an optional string that specifies how encoding and decoding errors are to be handled.

  • newline – a string; can be None, ‘’, ‘n’, ‘r’, or ‘rn’

  • closefd – if a filename is given closefd must be True otherwise, an error will be raised.

  • opener – A custom opener can be used by passing a callable as opener.

Open file and return a corresponding file object.

1.1.2. Close file

Use the close() method to close the file object after opening it.

Syntax:

f.close()

1.1.3. Read method

Use the read method to read the whole of a small file.

Syntax:

fileobject.read(size)
Parameters:

size – the number of characters (in text mode) or bytes (in binary mode) that are read; default 0 or omitted for whole file.


1.2. Context manager approach

The recommended approach for opening files is to use a context manager, “with … as …”, so that the file is closed automatically.
The code below reads the whole file and prints it.
filepath = "files/12days.txt"
with open(filepath, "r") as f:
    f_contents = f.read()
    print(f_contents)

1.3. Readlines

To read all the lines of a file into a list, list(f) or f.readlines() can be used.
Use readlines to create a list of lines of the file.

Syntax:

f.readlines(size)
Parameters:

size – optional; the number of characters or bytes returned exceed the size number, no more lines will be returned after that are returned.

filepath = "files/12days.txt"
with open(filepath, "r") as f:
    f_contents = f.readlines()
    print(f_contents)
The code above prints a list of lines returned by f.readlines().
['1 partridge in a pear tree\n', '2 turtle-doves\n', ...]

1.4. Iterating through the file

Use for line in f to efficiently iterate over the lines of the file.
This prints each line.
filepath = "files/12days.txt"
with open(filepath, "r") as f:
    for f_line in f:
        print(f_line, end="")

1.5. Write to a file

Use w as the mode to write to a file.
The code below writes “Test” to the file called “new_file.txt”.
If the file exists, it overwrites it.
If the file doesn’t exist, it creates it.
filepath = "files/new_file.txt"
with open(filepath, "w") as f:
    f.write("Test")

1.6. Appending to a text file

Use a as the mode to append to the end of a file.
If the file exists, it appends it.
If the file doesn’t exist, it creates it.
In the code below, the file is first opened in “w” mode to clear it and write to it.
Then the file is opened in “a” mode to add text to the end of it.
“n” add a line ending to put the second text on a next line.
filepath = "files/new_file.txt"
# overwrite file if it exists
with open(filepath, "w") as f:
    f.write("Test 1")
# open again for appending
with open(filepath, "a") as f:
    f.write("\nTest 2")

1.7. Copying parts of a text file

In the code below, rf is the read file object.
wf is the file object for writing.
Multiple lines can be written to the same file within the with open context mamnager.
The code below copies each line of the file 12days.txt to the file 12days_copy.txt.
rfilepath = "files/12days.txt"
wfilepath = "files/12days_copy.txt"
with open(rfilepath, "r") as rf:
    with open(wfilepath, "w") as wf:
        for line in rf:
            wf.write(line)
1 partridge in a pear tree
2 turtle-doves
3 French hens
...
Every second line can be copied by enumerating the file object, rf, then using the modulus operator, %, to get every second line.
step = 2
rfilepath = "files/12days.txt"
wfilepath = "files/12days_copy.txt"
with open(rfilepath, "r") as rf:
    with open(wfilepath, "w") as wf:
        for lineno, f_line in enumerate(rf):
            if lineno % step == 0:
                wf.write(f_line)
1 partridge in a pear tree
3 French hens
5 golden rings
...