#1
|
|||
|
|||
Error except syntax error
the file that it is trying to call does not exist.
I am looking to catch the IO error if it is present and then create the file. Code:
def main(): with open('C:\Users\AC30419\Documents\test.txt','r+') as f: except: crt.Diaglog.MessegeBox('error') main() Code:
def main(): with open('C:\Users\AC30419\Documents\test.txt','w') as f: pass main() |
#2
|
|||
|
|||
Okay the error in my way was not using the try command before the with statement thanks
|
#3
|
||||
|
||||
Quote:
Also, indentation matters in Python. Here's an example of correct indentation: Code:
# $language = "Python" # $interface = "1.0" def main(): # Open a file and read all of its contents into a variable import os strHome = os.path.expanduser("~") strPathToFile = "{0}/Documents/test.txt".format(strHome) strPathToFile = strPathToFile.replace("\\", "/") strContents = "" try: with open(strPathToFile, "r") as objFile: strContents = objFile.read() except Exception as objInst: crt.Dialog.MessageBox( "Error attempting to read file:\n\n{0}".format( str(objInst))) return # If we get here, we were able to read all of the file # data successfully into the variable: strContents crt.Dialog.MessageBox("Contents of the file:\r\n\r\n{0}".format( strContents)) main()
__________________
Jake Devenport VanDyke Software Technical Support YouTube Channel: https://www.youtube.com/vandykesoftware Email: support@vandyke.com Web: https://www.vandyke.com/support |
#4
|
|||
|
|||
Another option as well instead of using exceptions would be to use os.path.exists to check if the file is there or not. Something like this should work:
Code:
# $language = "Python" # $interface = "1.0" def main(): # Open a file and read all of its contents into a variable import os strHome = os.path.expanduser("~") strPathToFile = os.path.join(strHome,"/Documents/test.txt") if os.path.exists(strPathToFile): # File exists, read contents strContents = open(strPathToFile, "r").read() else: # File doesn't exist crt.Dialog.MessageBox( "Error attempting to read file:\n\n{0}".format( str(objInst))) return # If we get here, we were able to read all of the file # data successfully into the variable: strContents crt.Dialog.MessageBox("Contents of the file:\r\n\r\n{0}".format( strContents)) main() |
![]() |
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
Thread Tools | |
Display Modes | Rate This Thread |
|
|