13.2. File Open

  • open() - Opens file for reading or writing

  • By default opens file in read text mode

  • 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

13.2.1. Open

  • open() - Opens file for reading or writing

  • By default opens file in read text mode

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

13.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'

13.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'

13.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'

13.2.5. Recap

  • open() - Opens file for reading or writing

  • By default opens file in read text mode

  • 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