TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python IOError Fix, os.path.exists

Review IOError. Use os.path.exists and the try-raise construct.
IOError. File handling is fraught with errors. A file may not exist. It may not be accessible. In Python we encounter an IOError in these situations. We can prevent, or simply handle, IOErrors.
Example. This program causes an IOError to occur. The file "nope.txt" is most likely not present on the computer. The open() method raises an IOError with the "No such file or directory" message.
Python program that causes IOError # An invalid path. name = "/nope.txt" # Attempt to open the file. with open(name) as f: print(f.readline()) Output Traceback (most recent call last): File "...", line 7, in <module> with open(name) as f: IOError: [Errno 2] No such file or directory: '/nope.txt'
Exists. Next, we can prevent the IOError from happening by first testing the path.exists() method. This returns true if the file exists, and false otherwise. Here, the method returns false—so the open() method is never reached.

And: No error is ever encountered, because we avoid trying to open the file in the first place.

Python program that uses os.path.exists import os # A file that does not exist. name = "/nope.txt" # See if the path exists. if os.path.exists(name): # Open the file. with open(name) as f: print(f.readline())
Except example. This example uses a try-raise construct to capture errors. When the open() method raises an error, control flow enters the except-block. The Python program does not terminate. The error is trapped and handled with grace.Error
Python program that handles IOError try: # Does not exist. name = "/nope.txt" # Attempt to open it. with open(name) as f: print(f.readline()) except IOError: # Handle the error. print("An error occurred") Output An error occurred
Summary. Part of handling files is handling errors. The two tasks cannot be easily separated. In Python the IOError is an important file-handling error. And we can handle or fix it in many ways.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf