Python file read and write operation example

  • 2020-04-02 13:32:43
  • OfStack

1. OS module and shutil module are commonly used in python for operating files and folders.
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 in the specified directory :os.listdir()
Function to delete a file :os.remove()
4. Remove 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 whether it is an absolute path: os.path. Isabs ()
Verify that the given path exists :os.path. Exists ()
9. Returns the directory name and file name of a path :os.path.split()        
Example:

os.path.split('/home/swaroop/byte/code/poem.txt')  Results: ('/home/swaroop/byte/code', 'poem.txt')

10. Separate 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. Gives the line terminator used by the current platform :os.linesep       Windows USES '\r\n', Linux USES '\n' and Mac USES '\r'
16. Indicates the platform you are using: os.name             For Windows, it's 'nt' and for Linux/Unix users, it's 'posix'
17. Rename: os.rename(old, new)
18. Create multiple levels of directories: os.makedirs(r"c: \python\test")
19. Create a single directory: os.mkdir("test")
20. Get file properties: os.stat(file)
21. Modify file permissions and timestamp: os.chmod(file)
22. Terminate the current process: os.exit()
23. Get file size: os.path.getsize(filename)
Two, the document operation method daqo
1. OS. Mknod (" test. TXT ")               Create an empty file
2. The fp = open (" test. TXT ", w)         Open a file directly and create a file if the file does not exist
3. About the open mode:
w : open as a write, 
a : opens in append mode  ( from  EOF  start ,  Create new files if necessary )
r+ : opens in read/write mode 
w+ : opens in read/write mode  ( see  w )
a+ : opens in read/write mode  ( see  a )
rb : opens in binary read mode 
wb : opens in binary write mode  ( see  w )
ab : opens in binary append mode  ( see  a )
rb+ : opens in binary read/write mode  ( see  r+ )
wb+ : opens in binary read/write mode  ( see  w+ )
ab+ : opens in binary read/write mode  ( see  a+ )

Fp. Read ([size])                                         #size is the length read, in byte
Fp. Readline ([size])                                 # reads a line. If size is defined, it is possible to return only part of the line
Fp. Readlines ([size])                               Take each line of the file as a member of a list and return the list. It's actually done internally by looping through readline(). If you supply the size parameter, size is the total length of the read, which means that you may read only a portion of the file.
Fp. Write (STR)                                             Write () does not add a new line after STR
Fp. Writelines (seq)                                   Write the entire contents of seq to a file (multiple lines written at once). This function also just writes faithfully, not adding anything after each line.
Fp. Close ()                                                   Close the file. Python automatically closes a file when it's not in use, but that's not guaranteed, and it's best to get into the habit of doing it yourself.   A ValueError occurs if a file is manipulated after closing
Fp. Flush ()                                                   Write the contents of the buffer to the hard disk
Fp. Fileno ()                                                 Return a long integer "file label"
Fp. Isatty ()                                                 Is the file a terminal device file (on Unix systems)
Fp. Tell ()                                                     Returns the current location of the file action tag, starting at the beginning of the file
Fp. Next ()                                                     # returns the next line and displaces the file action flag to the next line. Use a file for... Statements such as in file are traversed by calling the next() function.
Fp. Seek (offset, whence [])                       Move the file mark to the offset position. This offset is usually calculated relative to the beginning of the file and is usually positive. But if provides whence parameter is not necessarily, whence may be computed on the basis of 0 said from the beginning, 1 origin calculation for the current position. 2 means to calculate with the end of the file as the origin. Note that if the file is opened in a or a+ mode, the file action flag is automatically returned to the end of the file each time a write is made.
Fp. Truncate ([size])                                 Crop the file to the specified size, by default, to the location of the current file action mark. If the size is larger than the size of the file, it may not change the file according to the system, it may fill the file to the corresponding size with 0, or it may add some random contents.
Three, directory operation method daquan
1. Create a directory
OS. The mkdir (" file ")                                    
2. Copy files:
Shutil. Used by copyfile (" oldfile ", "newfile")               #oldfile and newfile can only be files
Shutil. Copy (" oldfile ", "newfile")                       #oldfile can only be a folder, and newfile can be a file or a target directory
3. Copy folders:
4. Shutil. Copytree (" olddir ", "newdir")               Both #olddir and newdir can only be directories, and newdir must not exist
5. Rename files (directories)
OS. Rename (" oldname ", "newname")                           # files or directories use this command
6. Move files (directories)
Shutil. Move (" oldpos ", "newpos")    
7. Delete files
OS. Remove (" file ")
8. Delete the directory
OS. Rmdir (" dir ")                                                         Only empty directories can be deleted
Shutil. Rmtree (" dir ")                                               Empty directory, the contents of the directory can be deleted
9. Convert directories
OS. The chdir (" path ")                                                       # change the path
4. Examples of comprehensive operation of documents
Add '_fc' to all images in the folder
Python code:
# -*- coding:utf-8 -*-
import re
import os
import time
#str.split(string) Split string 
#' connector '.join(list)  Group the list into a string 
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) # Separate directories and files 
        lists = file_path[1].split('.') # Split the file with the file extension 
        file_ext = lists[-1] # Take the suffix name ( List slice operation )
        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 # Notice the i It's a trap 
        # or 
        #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() It's useful for path processing 
img_dir = 'D:\xx\xx\images'
img_dir = img_dir.replace('\','/')
start = time.time()
i = 0
change_name(img_dir)
c = time.time() - start
print(' Program running time :%0.2f'%(c))
print(' In total  %s  image '%(i))

Output results:
 Program running time :0.11
 In total  109  image 


Related articles: