Python3 抛出异常 #!/usr/bin/python3 def functionName( level ): if level <1: raise Exception(level) # The code below to this would not be executed # if we raise the exception return level try: l = functionName(-10) print ("level = ",l) except Exception as e: print ("error in level argument",e.args[0])
Python3 单个异常 #!/usr/bin/python3 # Define a function here. def temp_convert(var): try: return int(var) except ValueError as Argument: print ("The argument does not contain numbers\n", Argument) # Call above function here. temp_convert("xyz")
Python3 Try Finally 实例 #!/usr/bin/python3 try: fh = open("testfile", "w") try: fh.write("This is my test file for exception handling!!") finally: print ("Going to close the file") fh.close() except IOError: print ("Error: can\'t find file or read data")
Python3 通过索引迭代 #!/usr/bin/python3 fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print ('Current fruit :', fruits[index]) print ("Good bye!")
Python3 Write 权限 #!/usr/bin/python3 try: fh = open("testfile", "r") fh.write("This is my test file for exception handling!!") except IOError: print ("Error: can\'t find file or read data") else: print ("Written content in the file successfully")
Python3 os 模块 Write 方法 # !/usr/bin/python3 import os, sys # Open a file fd = os.open( "f1.txt", os.O_RDWR|os.O_CREAT ) # Write one string line = "this is test" # string needs to be converted byte object b = str.encode(line) ret = os.write(fd, b) # ret consists of number of bytes written to f1.txt print ("the number of bytes written: ", ret) # Close opened file os.close( fd) print ("Closed the file successfully!!")
Python3 os 模块 Tmpfile 方法 # !/usr/bin/python3 import os # The file has no directory entries associated with it and will be # deleted automatically once there are no file descriptors. tmpfile = os.tmpfile() tmpfile.write('Temporary newfile is here.....') tmpfile.seek(0) print tmpfile.read() tmpfile.close
Python3 os 模块 Symlink 方法 #!/usr/bin/python3 import os src = '/usr/bin/python3' dst = '/tmp/python' # This creates a symbolic link on python in tmp directory os.symlink(src, dst) print ("symlink created")