[Reprint]python File and directory operation method Daquan (including all file names under the Change folder instance)

Source: Internet
Author: User
Tags readline python script

http://blog.csdn.net/u010159842/article/details/53084067

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:

    1. W: Open in write mode,
    2. A: Open in Append mode (starting with EOF and creating a new file if necessary)
    3. r+: Open in read-write mode
    4. w+: Open in read/write mode (see W)
    5. A +: Open in read/write mode (see a)
    6. RB: Open in binary read mode
    7. WB: Opens in binary write mode (see W)
    8. AB: Open in binary append mode (see a)
    9. rb+: Open in binary read/write mode (see r+)
    10. wb+: Open in binary read/write mode (see w+)
    11. 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:

  1. #-*-Coding:utf-8-*-
  2. Import re
  3. Import OS
  4. Import time
  5. #str. Split (string) split string
  6. # ' connectors '. Join (list) to make a list of strings
  7. def change_name (path):
  8. Global I
  9. If not os.path.isdir (path) and not os.path.isfile (path):
  10. return False
  11. if Os.path.isfile (path):
  12. File_path = os.path.split (path) #分割出目录与文件
  13. Lists = file_path[1].split ('. ') #分割出文件与文件扩展名
  14. File_ext = lists[-1] #取出后缀名 (list slice operation)
  15. Img_ext = [' bmp ',' jpeg ', 'gif ', 'psd ',' png ',' jpg ']
  16. if File_ext in img_ext:
  17. Os.rename (path,file_path[0]+'/' +lists[0]+' _fc. ' +file_ext)
  18. i+=1 #注意这里的i是一个陷阱
  19. #或者
  20. #img_ext = ' bmp|jpeg|gif|psd|png|jpg '
  21. #if file_ext in Img_ext:
  22. # print (' OK---' +file_ext)
  23. elif Os.path.isdir (path):
  24. For x in os.listdir (path):
  25. Change_name (Os.path.join (path,x)) #os. Path.join () is useful in path processing
  26. Img_dir = ' d:\\xx\\xx\\images '
  27. Img_dir = img_dir.replace (' \ \ ', '/')
  28. Start = Time.time ()
  29. i = 0
  30. Change_name (Img_dir)
  31. c = Time.time ()-Start
  32. Print (' program run time:%0.2f '% (c))
  33. Print (' total processed%s picture '% (i))

Output Result:

    1. Program run time:0.11
    2. Processed 109 Pictures in total

[Reprint]python File and directory operation method Daquan (including all file names under the Change folder 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.