Python Learning Notes Read File OS Module Exception Handling with as Syntax Example

  • 2021-06-28 09:22:47
  • OfStack

Examples of Python learning notes are described in this paper, including reading files, OS modules, exception handling, and with as syntax.Share it for your reference, as follows:

File Read


# read file 
f = open("test.txt","r")
print(f.read()) # Print file contents  
# Close File 
f.close()

Get absolute path to file: OS module

os.environ["xxx"] Get system environment variables
os.getcwd Get the current python script working path
os.getpid() Get the current process ID
os.getppid() Get parent process ID

abnormal


# read file 
f = None
try:
  f = open("test.txt", "r")
  print(f.read())
except BaseException:
  print(" File not found ")
finally:
  if f is not None:
    f.close()

with as Syntax


# read file 
with open("test.txt","r") as f:
  print(f.read())
  f.close()

More readers interested in Python-related content can view this site's topics: Python File and Directory Operation Skills Summary, Python Text File Operation Skills Summary, Python Data Structure and Algorithms Tutorial, Python Function Usage Skills Summary, Python String Operation Skills Summary, and Python Introduction and Advanced Classic Tutorial.

I hope that the description in this paper will be helpful to everyone's Python program design.


Related articles: