Python file and Directory operations method Daquan (with instance)

Source: Internet
Author: User

One, python in the file, folder operations often used in the OS module and Shutil module common methods.

1 get the current working directory, that is, the directory path of the current Python script work: OS.GETCWD ()2 returns all files and directory names under the specified directory name: Os.listdir ()3 function to delete a file: Os.remove ()4 Delete Multiple directories: Os.removedirs (r "C:\python")5 verifies whether the given path is a file: Os.path.isfile ()6 Verify that the given path is a directory: Os.path.isdir ()7 determine if it is an absolute path: Os.path.isabs ()8 Verify that the given path is really saved: os.path.exists ()9Returns the directory name and file name of a path: Os.path.split () eg Os.path.split ('/home/swaroop/byte/code/poem.txt') Results: ('/home/swaroop/byte/code','Poem.txt'). Detach extension: Os.path.splitext ()Ten Get path name: Os.path.dirname () One Get file name: Os.path.basename () A Run shell command: Os.system () - Read and SET environment variables: os.getenv () and os.putenv () -Gives the line terminator used by the current platform: Os.linesep Windows uses'\ r \ n', Linux uses'\ n'and Mac uses'\ r' theIndicates the platform you are using: Os.name for Windows, it is'NT', and for Linux/unix users, it is'POSIX' - Rename : Os.rename (old, new) - Create a multilevel directory: Os.makedirs (r "C:\python\test") - Create a single directory: Os.mkdir ("Test") + get file attributes: Os.stat (file) - modify file permissions and timestamps: Os.chmod (file) + Terminate Current process: Os.exit () AGet File Size: os.path.getsize (filename)

Second, the file operation method Daquan:
1.os.mknod ("Test.txt") #创建空文件
2.FP = open ("Test.txt", W) #直接打开一个文件, create file If file does not exist
3. About open mode:

w: Open as Write, a: Open in Append mode (start with EOF, create new file if necessary) R+: Open w+: Open in read/write mode(see W) a+: Open in read/write mode (see a) RB: Open WB in binary read mode: Open in binary write mode (see W) AB: Open in binary append mode (see a) RB+: Open in binary read/write mode (see r+ ) WB+: Open in binary read/write mode (see w+ ) ab+: Open in binary read/write mode (see A +)

fp.read ([size]) #size is the length of the read, in bytes fp.readline ([size]) #read a line, if a size is defined, it is possible to return only part of a rowfp.write (str) #writes STR to a file, write () does not add a newline character after Strfp.close () #close the file. Python will automatically close files after a file is not used, but this feature is not guaranteed and it is best to develop a habit of shutting them down. If a file is closed and then manipulated, it generates ValueErrorFp.flush () #write the contents of the buffer to the hard disk Fp.tell () #returns the current position of the file action tag, starting with the origin of the fileFp.next () #returns the next line and shifts the file action marker to the next line. When a file is used for a statement such as for ... in file, it is called the next () function to implement the traversal. Fp.seek (offset[,whence]) #moves the file-action marker to the location of offset. This offset is generally relative##于文件的开头来计算的, usually a positive number. However, if the whence parameter is provided, the whence can be##以为0表示从头开始计算, 1 indicates the origin is calculated at the current position. 2 indicates the origin of the end of the file is counted.#count. Note that if the file is opened in a or a + mode, the file action tag will automatically return each time the write operation#to the end of the file. fp.truncate ([size]) #The file is cut to the specified size, the default is the location of the current file operation tag. If#size is larger than the file, depending on the system may not change the file, it may be 0 files to the corresponding#size, it may also be added to some random content. 

Three, directory operation method Daquan

1. Create Directory Os.mkdir ("file")2. Copy files: Shutil.copyfile ("Oldfile","NewFile")#Oldfile and NewFile can only be files .Shutil.copy ("Oldfile","NewFile")#Oldfile can only be a folder, NewFile may be a file, or it can be a destination directory3. Copy folder:4.shutil.copytree ("Olddir","Newdir")#Olddir and Newdir can only be directories, and newdir must not exist5. Rename file (directory) Os.rename ("oldname","newname")#the file or directory is used by this command6. moving files (directories) Shutil.move ("Oldpos","Newpos")7. Delete File Os.remove ("file")8. Delete directory Os.rmdir ("dir")#only empty directories can be deletedShutil.rmtree ("dir")#empty directories, contents of the directory can be deleted9. Convert Catalog Os.chdir ("Path")#Change Path

Iv. Examples of comprehensive documentation operations

Add ' _fc ' to all picture names under folder
Python code:

#-*-coding:utf-8-*-ImportReImportOSImport Time#str.split (String) split string#' connectors '. Join (list) to make a list of stringsdefchange_name (path):GlobalIif  notOs.path.isdir (PATH) and  notos.path.isfile (path):returnFalseifos.path.isfile (path): File_path= Os.path.split (path)#splitting out directories and filesLists = File_path[1].split ('.')#splitting out files with file name extensionsFile_ext = Lists[-1]#Remove suffix name (list slice operation)Img_ext = ['BMP','JPEG','gif','PSD','PNG','jpg']        ifFile_extinchimg_ext:os.rename (Path,file_path[0]+'/'+lists[0]+'_fc.'+file_ext) I+=1#Note that I here is a trap.        #or        #img_ext = ' bmp|jpeg|gif|psd|png|jpg '        #if File_ext in Img_ext:        #print (' OK---' +file_ext)    elifOs.path.isdir (path): forXinchOs.listdir (path): Change_name (Os.path.join (path,x))#Os.path.join () is useful for path processingImg_dir='d:\\xx\\xx\\images'Img_dir= Img_dir.replace ('\\','/') Start=time.time () I=0change_name (img_dir) C= Time.time ()-StartPrint('program run time:%0.2f'%(c))Print('processed%s picture in total'% (i))

Python file and Directory operations method Daquan (with instance)

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.