Python file and directory manipulation function summary

  • 2020-04-02 13:50:35
  • OfStack

Operations on files, folders (file manipulation functions) in python need to involve 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 in the specified directory: OS. Listdir ()
The delete () function is used to delete a file: OS. The remove ()
Delete multiple directories: Os.removedirs (r "c: \python")
Verify if the given path is a file: OS. Path. Isfile ()
Verify that the given path is a directory: OS. The path. The isdir ()
Determine if the path is absolute: OS. Path. Isabs ()
Verify whether the given path is actually in existence: OS. The path. The exists ()
Returns the directory name and file name of a path: OS. The path. The split () Eg OS. Path. The split ('/home/swaroop/byte/code/poem TXT ') results: '/ home/swaroop/byte code', 'poem. TXT)
Split extension: OS. Path. Splitext ()
Get path name: OS. The path. The dirname ()
Get file name: OS. The path. The basename ()
Run the shell command: OS. The system ()
Read and set environment variables: OS. The 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'
Indicate the platform you are using: OS. The name For Windows, it's 'nt' and for Linux/Unix users, it's 'posix'
Rename: Os.rename (old, new)
Create multilevel directories: Os.makedirs (r "c: \python\test")
Create a single directory: OS. The mkdir (" test ")
Get file properties: OS. Stat (file)
Modify file permissions and timestamps: OS. Chmod (file)
Terminate the current process: OS. The exit ()
Get file size: OS. Path. Getsize (filename)

File operation:

OS. Mknod (" test. TXT ") Create an empty file
Fp = open (" test. TXT ", w) Open a file directly and create a file if the file does not exist

About the open mode:

W opens as a write,
A opens in append mode (starting with EOF and creating 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.

Directory operation:

OS. The mkdir (" file ") Create a directory

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

Copy folder:

Shutil. Copytree (" olddir ", "newdir") Both olddir and newdir can only be directories, and newdir must not exist

Rename files (directories)

OS. Rename (" oldname ", "newname") Files or directories use this command

Moving files (directories)

Shutil. Move (" oldpos ", "newpos")

Delete the file

OS. Remove (" file ")

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

Conversion directory

OS. The chdir (" path ") Change the path

Relevant example
1 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 all, 109 images were processed


Related articles: