Examples of functions for common file operations in Python

# -*-coding:utf8 -*-  
  
'''''
    Examples of common file operations in Python
 
    Pathname access functions in the os.path module
    separate
    basename() removes the directory path and returns the filename
    dirname() removes the filename and returns the directory path
    join() combines the separated parts into a single pathname
    split() returns (dirname(), basename()) tuple
    splitdrive() returns a (drivename, pathname) tuple
    splitext() returns a (filename, extension) tuple
 
    information
    getatime() returns the last access time
    getctime() returns the file creation time
    getmtime() returns the most recent file modification time
    getsize() returns the file size in bytes
 
    Inquire
    exists() Whether the specified path (file or directory) exists
    isabs() specifies whether the path is an absolute path
    isdir() specifies whether the path exists and is a directory
    isfile() specifies whether the path exists and is a file
    islink() specifies whether the path exists and is a symbolic link
    ismount() specifies whether the path exists and is a mount point
    samefile() whether two pathnames point to the same file
     
    os.path.isdir(name): Determine if name is a directory, if name is not a directory, return false
    os.path.isfile(name): Determine if name is a file, and return false if name does not exist
    os.path.exists(name): determine whether a file or directory name exists
    os.path.getsize(name): Get the file size, if name is a directory, return 0L
    os.path.abspath(name): get the absolute path
    os.path.normpath(path): canonical path string form
    os.path.split(name): splits filenames from directories (in fact, if you use directories at all, it will also split the last directory as a filename, and it won't tell if a file or directory exists)
    os.path.splitext(): separate filename and extension
    os.path.join(path,name): join a directory with a filename or directory
    os.path.basename(path): returns the file name
    os.path.dirname(path): returns the file path
         
     
    File operations in the os module:
    os module properties
    linesep String used to separate lines in the file
    sep String used to separate file pathnames
    pathsep String used to separate file paths
    curdir String name of the current working directory
    pardir (current working directory) parent directory string name
     
    1. Rename: os.rename(old, new)
     
    2. Delete: os.remove(file)
 
    3. List the files in the directory: os.listdir(path)
 
    4. Get the current working directory: os.getcwd()
 
    5. Change the working directory: os.chdir(newdir)
 
    6. Create a multi-level directory: os.makedirs(r"c:\python\test")
 
    7. Create a single directory: os.mkdir("test")
 
    8. Delete multiple directories: os.removedirs(r"c:\python") #Delete all empty directories under the last directory of the given path.
 
    9. Delete a single directory: os.rmdir("test")
 
    10. Get file attributes: os.stat(file)
 
    11. Modify file permissions and timestamps: os.chmod(file)
 
    12. Execute the operating system command: os.system("dir")
 
    13. Start a new process: os.exec(), os.execvp()
 
    14. Execute a program in the background: osspawnv()
 
    15. Terminate the current process: os.exit(), os._exit()
 
    16. Separate file name: os.path.split(r"c:\python\hello.py") --> ("c:\\python", "hello.py")
 
    17. Separate extension: os.path.splitext(r"c:\python\hello.py") --> ("c:\\python\\hello", ".py")
 
    18. Get the path name: os.path.dirname(r"c:\python\hello.py") --> "c:\\python"
 
    19. Get the file name: os.path.basename(r"r:\python\hello.py") --> "hello.py"
 
    20. Determine whether the file exists: os.path.exists(r"c:\python\hello.py") --> True
 
    21. Determine whether it is an absolute path: os.path.isabs(r".\python\") --> False
 
    22. Determine whether it is a directory: os.path.isdir(r"c:\python") --> True
 
    23. Determine whether it is a file: os.path.isfile(r"c:\python\hello.py") --> True
 
    24. Determine whether it is a link file: os.path.islink(r"c:\python\hello.py") --> False
 
    25. Get the file size: os.path.getsize(filename)
 
    26.*******:os.ismount("c:\\") --> True
 
    27. Search all files in the directory: os.path.walk()
 
    The shutil module operates on files:
    1. Copy a single file: shultil.copy(oldfile, newfle)
 
    2. Copy the entire directory tree: shultil.copytree(r".\setup", r".\backup")
 
    3. Delete the entire directory tree: shultil.rmtree(r".\backup")
 
    Temporary file operations:
    1. Create a unique temporary file: tempfile.mktemp() --> filename
 
    2. Open a temporary file: tempfile.TemporaryFile()
 
    In-memory file (StringIO and cStringIO) operations
    [4.StringIO] #cStringIO is a fast implementation module of StringIO module
 
    1. Create a memory file and write initial data: f = StringIO.StringIO("Hello world!")
 
    2. Read in memory file data: print f.read() #or print f.getvalue() --> Hello world!
 
    3. Want to write data to the memory file: f.write("Good day!")
 
    4. Close the memory file: f.close()
'''  
import them  
import os.path  
import unittest  
import time  
#import pygame  
  
class PyFileCommonOperatorTest(unittest.TestCase):  
    def __init__(self):  
        """constructor"""  
      
    def test01(self):  
        print os.linesep  
        print os.sep  
        print os.pathsep  
        print os.curdir  
        print os.pardir  
        print os.getcwd()  
        print 'unittest here'  
  
  
if __name__ == "__main__":  
    t = PyFileCommonOperatorTest()  
    t.test01()  

  

#Writing to read the file:  
#Read text file:   
input = open('data', 'r')#The second parameter is the default and can be omitted  
#Read binary file:   
input = open('data', 'rb')  
#Read all file contents:  
open('xxoo.txt').read()  
#read fixed bytes  
open('abinfile', 'rb').read(100)  
# read each line  
file_object.readlines()  

  Reprinted from: https://blog.csdn.net/scelong/article/details/6971917

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324978883&siteId=291194637