Python file operation methods

Source: Internet
Author: User

The operation of files, folders (file manipulation functions) in Python involves both the OS module and the Shutil module.   Get the current working directory, that is, the directory path of the current Python script work: OS.GETCWD ()   Returns all files and directory names under the specified directory name: os.listdir ()   function to delete a file: Os.remove ()   Delete multiple directories: Os.removedirs (r "C:\python")   Verify that the given path is a file: Os.path.isfile ()   Verify that the given path is a directory: Os.path.isdir ()   Determine if the path is absolute: Os.path.isabs ()   Verify that the given path is really saved: os.path.exists ()   Returns 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 ()   Get path name: Os.path.dirname ()   Return path normalized absolute path: Os.path.abspath ()   Get file name: Os.path.basename ()   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 use ' \ r \ n ', Linux uses ' \ n ' While Mac uses ' \ R '   Indicates the platform you're using: Os.name        for Windows, it's ' NT ', and for Linux/unix users, it's ' POSIX '   rename: Os.rename (old, new)   Create multilevel directory: Os.makedirs (r "C:\python\test")   Create a single directory: Os.mkdir ("Test")   Get file properties: OS.Stat (file)   Modify file permissions and timestamps: Os.chmod (file)   Terminate current process: Os.exit ()   Get file size: os.path.getsize (filename)     File operation: Os.mknod ("test.txt")         create empty file FP = open ("Test.txt", W)       open a file directly, create a file if the file does not exist   about open mode:  w      Open with write, a       Open in Append mode (starting with EOF, creating new files if necessary) r+      open in read-write mode w+      open in read-write mode (see W) A + & nbsp;    Open in read-write mode (see a) RB      open WB in binary read mode      open in binary write mode (see W) AB      opens in binary append mode (see a) rb+     opens 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为读取的长度, in bytes  fp.readline ([size])                  #读一行, if size is defined, it is possible to return only a portion of a row  fp.readlines ([size])                  #把文件每一行作为一个list的一个成员 and return to this list. In fact, its internal is through the Loop call ReadLine () to achieve. If you provide a size parameter, size is the total length of the read content, which means that it may be read only to a portion of the file.  fp.write (str)                        #把str写到文件中, write () does not add a line break after Str  fp.writelines (seq)              #把seq的内容全部写到文件中 (Multi-line write-once). This function simply writes faithfully and does not add anything behind each line.  fp.close ()                          #关闭文件. 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 after it is also manipulated, it generates Valueerror fp.flush ()                                        #把缓冲区的内容写入硬盘  fp.fileno ()                                         #返回一个长整型的 "file label"  fp.isatty ()                                         #文件是否是一个终端设备文件 (in Unix systems)  fp.tell ()                                           # Returns the current position of the file action tag, starting with the origin of the file  fp.next ()                                          #返回下一行, 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 calculated relative to the beginning of the file and is generally a positive number. However, if the whence parameter is provided, whence can be calculated from scratch for 0, and 1 for the current position as its origin. 2 means that the end of the file is calculated as the origin. Note that if the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is made.  fp.truncate ([size])                         #把文件裁成规定的大小, the default is the location that is cropped to the current file action tag. If the size of the file is larger, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add.     Directory Operations: Os.mkdir ("file")                     Create directory Copy file: Shutil.copyfile ("Oldfile", "NewFile")        oldfile and NewFile can only be file Shutil.copy ("OldfIle "," NewFile ")            oldfile can only be a folder, NewFile can be a file, It can also be the target directory Replication folder: Shutil.copytree ("Olddir", "Newdir")        olddir and Newdir can only be directories, And Newdir must not have a renamed file (directory) os.rename ("Oldname", "NewName")        Files or directories are used to move files (directories) shutil.move ("Oldpos", "Newpos")    Delete files os.remove ("file") to delete directories Os.rmdir ("dir") Only empty directories Shutil.rmtree ("dir")     empty directories, content directories can be deleted Os.chdir ("path")    change Path      Example    1 add all the picture names under the folder to the ' _fc '  python code:  #-*-coding:utf-8-*-import reimport osimport Time#str.split (String) splits the string # ' connector '. Join (list) to make a list of strings Def change_name (path):     global i     if not Os.path.isdir (path) and not Os.path.isfile (path):         return false    if os.path.isfile (path):         file_path = OS.PATH.SPlit (path) #分割出目录与文件         lists = File_path[1].split ('. ') #分割出文件与文件扩展名         file_ext = lists[-1] #取出后缀名 (list slicing operations)          img_ext = [' bmp ', ' jpeg ', ' gif ', ' psd ', ' png ', ' jpg ']         if File_ext in Img_ext:            os.rename ( path,file_path[0]+ '/' +lists[0]+ ' _fc. ' +file_ext)             i+=1 #注意这里的i是一个陷阱           #或者          #img_ext = ' bmp|jpeg|gif| Psd|png|jpg '          #if file_ext in img_ext:         #    print (' OK---' +file_ext)     elif Os.path.isdir ( Path):         for x in Os.listdir (path):             change_name (Os.path.join (path,x)) # Os.path.join () is useful for path processing   img_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 '% (i) ')   Output:  program run time: 0.11 total 109 images processed  

Python file operation methods

Related Article

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.