7.2. File Access Modes

7.2.1. Write

  • mode='wt' - write in text mode

  • mode='wb' - write in binary mode

  • mode='w' - write in text mode (alias to "wt")

  • mode='wt+' - open for updating (reading and writing)

  • mode='wb+' - open for updating (reading and writing)

  • mode='w+' - open for updating (reading and writing) (alias to "wt+")

FILE = r'/tmp/myfile.txt'
data = 'We choose to go to the Moon...'

with open(FILE, mode='w'):
    file.write(data)

7.2.2. Append

  • mode='at' - append in text mode

  • mode='ab' - append in binary mode

  • mode='a' - append in text mode (alias to "at")

  • mode='at+' - open for updating (reading and writing)

  • mode='ab+' - open for updating (reading and writing)

  • mode='a+' - open for updating (reading and writing) (alias to "at+")

FILE = r'/tmp/myfile.txt'
data = 'We choose to go to the Moon...'

with open(FILE, mode='a'):
    file.write(data)

7.2.3. Read

  • mode='rt' - read in text mode (default)

  • mode='rb' - read in binary mode

  • mode='r' - read in text mode (alias to "wt")

  • mode='rt+' - open for updating (reading and writing)

  • mode='rb+' - open for updating (reading and writing)

  • mode='r+' - open for updating (reading and writing) (alias to "rt+")

  • If no mode is specified, the default mode is "rt"

FILE = r'/tmp/myfile.txt'

with open(FILE):
    data = file.read()
FILE = r'/tmp/myfile.txt'

with open(FILE, mode='r'):
    data = file.read()

7.2.4. Exception Handling

FILE = r'/tmp/myfile.txt'

try:
    with open(FILE) as file:
        print(file.read())

except FileNotFoundError:
    print('File does not exist')

except PermissionError:
    print('Permission denied')

7.2.5. Assignments

7.2.5.1. File Access Error

English
  1. Using input() ask user for a file path

  2. Print file content

  3. Handle exception for not existing file

  4. Handle exception for not having sufficient permissions

Polish
  1. Używając input() zapytaj użytkownika o ścieżkę do pliku

  2. Wypisz zawartość pliku

  3. Obsłuż wyjątek dla nieistniejącego pliku

  4. Obsłuż wyjątek dla braku wystarczających uprawnień