Examples of functions for Python common file operations

Source: Internet
Author: User

#-*-coding:utf8-*-"Python common file Operation example os.path the path name Access function in the module separates basename () removes the directory path, returns the file name DirName ( Remove the file name and return to the directory path join () combines each part of the detach into a path name split () returns (DirName (), basename ()) tuple splitdrive () return (DriveName, pathn AME) tuple Splitext () returns (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) of the query exists () specifies whether the path (file or directory) exists Isabs () specifies whether the path is an absolute path isdir () specifies whether the path exists and           For a directory isfile () specifies whether the path exists and is a file Islink () that specifies whether the path exists and is a symbolic link ismount () Specifies whether the path exists and is a mount point Samefile () two path names pointing to the same file Os.path.isdir (name): Determine if Name is a directory, name is not a directory to return false Os.path.isfile (name): Determine if name is not a file, does not exist name also returns false OS . Path.exists (name): Determine if a file or directory exists name os.path.getsize: Gets the file size, if name is the directory that returns 0L Os.path.abspath (name): Gets the absolute path to the OS.     Path.normpath (PATH): Canonical path string form Os.path.split (name): Split file name and directory (in fact, if you use the directory completely, it will also separate the last directory as the file name, and it will not determine whether the file or directory exists) Os.path.splitext (): Separating file names from extendedExhibition name Os.path.join (path,name): Connection directory with file name or directory Os.path.basename (path): Return file name Os.path.dirname (path): Returns the path File operations in the OS module: OS module properties LINESEP string used to separate rows in a file the string Sep uses to separate the file path name pathsep the string used to separate the file path CurDir the current working directory character String name Pardir (current working directory) parent directory strings name 1. Renaming: Os.rename (old, new) 2. Delete: Os.remove (file) 3. list files in directory: OS.LISTD IR (PATH) 4. Get current working directory: OS.GETCWD () 5. Change the working directory: Os.chdir (newdir) 6. Create a multilevel directory: Os.makedirs (r "C:\python\test") 7. Create      Single directory: Os.mkdir ("Test") 8. Delete Multiple directories: Os.removedirs (r "C:\python") #删除所给路径最后一个目录下所有空目录.       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 command: Os.system ("dir") 13. Start a new process: Os.exec (), OS.EXECVP () 14. Executing the program in the background: OSSPAWNV () 15. Terminate the current process: Os.exit (), Os._exit () 16. Detach File Name: Os.pat H.split (r "c:\python\hello.py")--("C:\\python", "hello.py") 17. Detach Extension: Os.path.splitext (r "c:\python\hello.py")- ("C:\\python\\hello", ". Py") 18. Get Path name: Os.path.dIrname (r "c:\python\hello.py")--"C:\\python" 19. Get File Name: Os.path.basename (r "r:\python\hello.py")--"hello.py "20. Determine if the file exists: os.path.exists (r" c:\python\hello.py ")--and True 21. Determine if absolute path: 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 file: Os.path.isfile (r "c:\python\hello.py")-- True 24. Determine if it is a linked file: Os.path.islink (r "c:\python\hello.py")--25. Get File Size: os.path.getsize (filename) 2 6.*******:os.ismount ("c:\\")--True 27. Search all files in directory: Os.path.walk () shutil module operation on files: 1. Copying a single file: Shultil.copy (      Oldfile, Newfle) 2. Copy the entire tree: Shultil.copytree (r ". \setup", R ". \backup") 3. Delete entire directory tree: Shultil.rmtree (r ". \backup") Operations for temporary files: 1. Create a unique temporary file: tempfile.mktemp () and filename 2. Open temp file: Tempfile. Temporaryfile () memory files (Stringio and Cstringio) operation [4.StringIO] #cStringIO是StringIO模块的快速实现模块 1. Create a memory file and write the initial data: F = Str      Ingio.stringio ("Hello world!") 2. Read in memory file data: Print F.read () #或Print F.getvalue ()--Hello world!      3. Want the memory file to write data: F.write ("Good day!") 4. Close the memory file: F.close () "Import OS import os.path import unittest import time #import Pygame class Pyfilecommonopera Tortest (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 ()

  

#读文件的写法:  #读文本文件:   input = open (' Data ', ' R ') #第二个参数是默认的, can be added without  #读二进制文件:   input = open (' Data ', ' RB ')  # Read all file contents:  open (' Xxoo.txt '). Read ()  #读取固定字节  open (' abinfile ', ' RB '). Read (+)  #读每行  File_ Object.readlines ()  

Turn from: 6971917

Examples of functions for Python common file operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.