Sample code for functions that are common file operations in Python

  • 2020-04-02 09:43:31
  • OfStack

 
# -*-coding:utf8 -*- 
''' 
Python Common examples of file manipulation  
os.path  The pathname access function in the module  
 separated  
basename()  Remove directory path ,  Return file name  
dirname()  Remove file name ,  Return directory path  
join()  Group the separated parts into a path name  
split()  return  (dirname(), basename())  tuples  
splitdrive()  return  (drivename, pathname)  tuples  
splitext()  return  (filename, extension)  tuples  
 information  
getatime()  Returns the last access time  
getctime()  Returns the time the file was created  
getmtime()  Returns the last file modified  
getsize()  Return file size ( In bytes ) 
 The query  
exists()  The specified path ( File or directory ) If there is a  
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 refer to the same file  
os.path.isdir(name): judge name Is it a directory, name Return not the directory false 
os.path.isfile(name): judge name Is not a file, does not exist name Also return false 
os.path.exists(name): Determines whether a file or directory exists name 
os.path.getsize(name): Get the file size if name Directory return 0L 
os.path.abspath(name): Get the absolute path  
os.path.normpath(path): specification path String form  
os.path.split(name): Split the file name from the directory (in fact, if you use the directory entirely, it will also separate the last directory as the file name, and it won't tell if the file or directory exists)  
os.path.splitext(): Separate file name and extension  
os.path.join(path,name): Connect directories to file names or directories  
os.path.basename(path): Return file name  
os.path.dirname(path): Return file path  

os File operation in the module:  
os  The module properties  
linesep  String used to separate lines in a file  
sep  A string that separates file path names  
pathsep  A string used to separate file paths  
curdir  The string name of the current working directory  
pardir ( Of the current working directory ) Parent directory string name  
1. Rename: os.rename(old, new) 
2. Delete: os.remove(file) 
3. List files in directory: os.listdir(path) 
4. Get the current working directory: os.getcwd() 
5. Change working directory: os.chdir(newdir) 
6. Create multilevel directories: os.makedirs(r"c:pythontest") 
7. Create a single directory: os.mkdir("test") 
8. Delete multiple directories: os.removedirs(r"c:python") # Deletes all empty directories under the last directory given to the path.  
9. Delete a single directory: os.rmdir("test") 
10. Get file properties: os.stat(file) 
11. Modify file permissions and timestamps: os.chmod(file) 
12. Execute operating system commands: os.system("dir") 
13. Start a new process: os.exec(), os.execvp() 
14. Execute the program in the background: osspawnv() 
15. Terminate the current process: os.exit(), os._exit() 
16. Separate file name: os.path.split(r"c:pythonhello.py") --> ("c:\python", "hello.py") 
17. Split extension: os.path.splitext(r"c:pythonhello.py") --> ("c:\python\hello", ".py") 
18. Get path name: os.path.dirname(r"c:pythonhello.py") --> "c:\python" 
19. Get file name: os.path.basename(r"r:pythonhello.py") --> "hello.py" 
20. Determine whether the file exists: os.path.exists(r"c:pythonhello.py") --> True 
21. Determine if the path is absolute: os.path.isabs(r".python") --> False 
22. Determine if it is a directory: os.path.isdir(r"c:python") --> True 
23. Determine if it is a document: os.path.isfile(r"c:pythonhello.py") --> True 
24. To determine whether it is a link file: os.path.islink(r"c:pythonhello.py") --> False 
25. Get file size: os.path.getsize(filename) 
26.******* : os.ismount("c:\") --> True 
27. Search all files in the directory: os.path.walk() 
shutil Operation of the module on the file:  
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") 
 Operation of temporary files:  
1. Create a unique temporary file: tempfile.mktemp() --> filename 
2. Open temporary file: tempfile.TemporaryFile() 
 In-memory file ( StringIO and cStringIO ) operation  
[4.StringIO] #cStringIO is StringIO Quick module implementation module  
1. Create an in-memory file and write the initial data: f = StringIO.StringIO("Hello world!") 
2. Read in memory file data: print f.read() # or print f.getvalue() --> Hello world! 
3. To write data to an in-memory file: f.write("Good day!") 
4. Close memory file: f.close() 
''' 
import os 
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() 

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

Related articles: