14.2. File Open

  • open() - Opens file for reading or writing

  • By default opens file in read text mode

  • By default, text files are opened using UTF-8 encoding

  • You can specify different encoding using encoding parameter

  • FileNotFoundError - When file does not exist

  • IsADirectoryError - When trying to open a directory instead of a file

  • PermissionError - When trying to open a file without required permissions

14.2.1. Open

  • open() - Opens file for reading or writing

  • By default opens file in read text mode

>>> file = open('/tmp/myfile.txt')

14.2.2. FileNotFoundError

  • When file does not exist

  • When directory in which file should be created does not exist

>>> open('/tmp/notexisting/myfile.txt')
Traceback (most recent call last):
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/notexisting/myfile.txt'

14.2.3. IsADirectoryError

  • When trying to open a directory instead of a file

>>> open('/tmp')
Traceback (most recent call last):
IsADirectoryError: [Errno 21] Is a directory: '/tmp'

14.2.4. PermissionError

  • When trying to open a file without required permissions

  • On some systems, if you don't have permission to read a file, you'll can get FileNotFoundError instead (OS is hiding the fact that file even exists)

>>> open('/etc/sudoers')
Traceback (most recent call last):
PermissionError: [Errno 13] Permission denied: '/etc/sudoers'

14.2.5. Encoding

  • By default, text files are opened using UTF-8 encoding

  • You can specify different encoding using encoding parameter

  • On Windows some apps use cp1250 or cp1252 encoding

  • Everywhere else UTF-8 is used

  • If app wrote file using certain encoding you must use the same encoding to read it, otherwise you will get UnicodeDecodeError

  • 99.999% of websites on the internet use UTF-8 encoding

>>> file = open('/tmp/myfile.txt', encoding='utf-8')
>>> file = open('/tmp/myfile.txt', encoding='cp1250')

14.2.6. Recap

  • open() - Opens file for reading or writing

  • By default opens file in read text mode

  • By default, text files are opened using UTF-8 encoding

  • You can specify different encoding using encoding parameter

  • FileNotFoundError - When file does not exist

  • IsADirectoryError - When trying to open a directory instead of a file

  • PermissionError - When trying to open a file without required permissions