Fish Touching🐟🎣

Python File

Aug 4, 2022

# open()

Src
open() returns a  file object, and is most commonly used with two positional arguments and one keyword argument: open(filename, mode, encoding=None)

f = open('workfile', 'w', encoding="utf-8")

# with

It is good practice to use the  with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent  try- finally blocks:

>>> with open('workfile', encoding="utf-8") as f:
...     read_data = f.read()

>>> # We can check that the file has been automatically closed.
>>> f.closed
True

# write()

f.write(string) writes the contents of string to the file, returning the number of characters written.

>>> f.write('This is a test\n')
15

>>> value = ('the answer', 42)
>>> s = str(value)  # convert the tuple to string
>>> f.write(s)
18

# readline()

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.
This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''