I. File read and write:
1. Read the file:
Try: f = open (' D:\\1.txt ', ' R ') # reads plain file f = open (' d:\\1.jpg ', ' RB ') # reads binary file f.read () finally: if f:
f.close () with open (' D:\\1.txt ', ' R ') as F: # using with will automatically call close for lines in f.readlines (): # readlines can read a line of print (Line.strip ()) # Delete the "\ n" at the end of the import codecswith codecs.open (' D:\\1.txt ', ' r ', ' GBK ') as F: # Use Codecs to specify the encoding for Li NE in F.readlines ():
2. Write the file:
f = open (' D:\\1.txt ', ' W ') # Write bits wbf.write (' Hello, world! ') F.close ()
Two. operating files and directories:
Python's OS module encapsulates the operating system's directory and file operations, note that some of these functions are in the OS module, some in the Os.path module
Import Osprint Os.environ # Gets the operating system environment variable print os.getenv (' path ') # Gets the value of path in the environment variable print os.path.abspath ('. ') # View the absolute path of the current directory # Os.mkdir (' D:\\test ') # then create a directory #os.rmdir (' d:\\test ') # Delete a directory of print os.path.join (' d:\\test ', ' TT ') # combine two paths into one d:\test\ Ttprint os.path.split (' D:\\test\\1.txt ') # Split path (' D:\\test ', ' 1.txt ') print os.path.splitext (' d:\\test\\1.txt ') # Get Extended Name (' d:\\test\\1 ', '. txt ')
Three. Serialization
Python Learning Note (ix)-IO programming