Python file and Directory operations method Daquan (with instance)

Source: Internet
Author: User
Tags readline python script

This article mainly introduces the Python file and directory operation methods, concise summary of the file and directory operations commonly used modules, methods, and listed a comprehensive example, the need for friends can refer to the following

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. Return all files and directories 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. Verify that 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 ()
9. Returns the directory name and file name of a path: Os.path.split () eg os.path.split ('/home/swaroop/byte/code/poem.txt ') Result: ('/home/swaroop/byte/ Code ', ' Poem.txt ')
10. Detach extension: Os.path.splitext ()
11. Get Path name: Os.path.dirname ()
12. Get File Name: Os.path.basename ()
13. Run the shell command: Os.system ()
14. Read and SET environment variables: os.getenv () and os.putenv ()
15. Give the line terminator used by the current platform: os.linesep Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '
16. Indicate the platform you are using: Os.name for Windows, it is ' NT ', and for Linux/unix users, it is ' POSIX '
17. Renaming: Os.rename (old, new)
18. Create a multilevel directory: Os.makedirs (r "C:\python\test")
19. Create a single directory: Os.mkdir ("Test")
20. Get File attributes: Os.stat (file)
21. Modify file permissions and timestamps: Os.chmod (file)
22. Terminate the current process: Os.exit ()
23. Get 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 in read-write mode 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: Two The binary append mode opens (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为读取的长度, in bytes
Fp.readline ([size]) #读一行, if size is defined, it is possible to return only part of a row
Fp.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns the 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 newline character 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 and then manipulated, it generates VALUEERROR
Fp.flush () #把缓冲区的内容写入硬盘
Fp.fileno () #返回一个长整型的 "file label"
Fp.isatty () #文件是否是一个终端设备文件 (on UNIX systems)
Fp.tell () #返回文件操作标记的当前位置, 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]) #将文件打操作标记移到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.
Three, directory operation method Daquan
1. Create a Directory
Os.mkdir ("file")
2. Copy the file:
Shutil.copyfile ("Oldfile", "NewFile") #oldfile和newfile都只能是文件
Shutil.copy ("Oldfile", "NewFile") #oldfile只能是文件夹, NewFile can be a file, or it can be a destination directory
3. Copy the folder:
4.shutil.copytree ("Olddir", "Newdir") #olddir和newdir都只能是目录, and newdir must not exist
5. Renaming files (directories)
Os.rename ("Oldname", "NewName") #文件或目录都是使用这条命令
6. Moving Files (directories)
Shutil.move ("Oldpos", "Newpos")
7. deleting files
Os.remove ("file")
8. Deleting a directory
Os.rmdir ("dir") #只能删除空目录
Shutil.rmtree ("dir") #空目录, contents of the directory can be deleted
9. Converting a directory
Os.chdir ("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))

The output is as follows:

Program run time: 0.11109 Photos

Transferred from: https://www.jb51.net/article/48001.htm

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.