Use of Python standard library os (operation of system variables, operation of files and directories, execution of commands and management of processes)

Posted by NICKKKKK on Sat, 13 Nov 2021 03:07:43 +0100

Common function combination (continuous update)

List of common functions of os module

1. File operation

  • os.remove(path) # is used to delete the files in the specified path. If the specified path is a directory, an OSError is thrown.
  • os.rename(src, dst) # name the file or directory, and rename the corresponding file
  • os.renames(old, new) # is used to recursively rename directories or files. Similar to rename(). You can rename either the file or its parent directory name
  • os.path.getmtime(path) # returns the most recent file modification time, in seconds from the new era to the time of access.
  • Os.path.gettime (path) # returns the creation time of the file path, the number of seconds from the new era to the access time.
  • os.path.getsize(path) # returns the file size. If the file does not exist, it returns an error. If it is a directory, it returns 0.

2. Directory operation class

  • os.mkdir(path[, mode]) # creates directories in digital permission mode. The default mode is 0777 (octal).
  • os.makedirs(path, mode=0o777) # is used to create directories recursively. Like mkdir(), but all folders created need to contain subdirectories.
  • os.rmdir(path) # delete the path directory (only the first level directory can be deleted, such as' F:\XXX\SSS'), and only the SSS directory can be deleted
  • OS. Removediers (path) # delete multi-level directories (such as' F:\XXX\SSS'), which must be empty. Delete SSS and FFF directories

3. Judgment

  • os.path.isfile(path) # determines whether the path is a file
  • os.path.isdir(path) # determines whether the path is a directory
  • os.path.exists(path) # if the path path exists, return True; Returns False if the path does not exist.
  • os.path.isabs(path) # determines whether it is an absolute path, that is, in the WIndow system, if the input string starts with "/", os.path.isabs() will return True

4. Environment variable query / acquisition class

  • os.name() # returns the representative character of the currently used platform, which is represented by 'nt' for Windows and 'posix' for Linux
  • os.stat(path) # get file or directory information
  • os.linesep() # the string used by the current platform to separate (or terminate) rows. It can be a single character, such as' \ n 'on POSIX, or multiple characters, such as' \ r\n' on Windows. When writing files opened in text mode (default mode), do not use os.linesep as the line terminator, but use a '\ n' instead on all platforms.
  • os.sep() # displays the path separator under the current platform, which is' / 'on POSIX and' \ 'on Windows
  • os.pathsep() # operating system is usually used to separate characters in different parts of search PATH (such as PATH), such as': 'on POSIX and'; 'on Windows. It is also available in os.path.

5. Address / path class

  • os.getcwd() # get the current working path
  • os.path.abspath(path) # returns the absolute path of path
  • os.listdir(path) # returns the list of all files in the path directory
  • os.path.basename(path) # returns the file name, which is purely a string processing logic. Path errors are also acceptable
  • os.path.dirname(path) # returns the file path
  • os.path.split(path) # divides the path into dirname and basename, and returns a tuple
  • Os.path.splittext (path) # splits the path and returns the tuple of the path name and file extension
  • os.path.join(path1[, path2 [,...]]) # combines the directory and file name into one path. 1. If the initial letter of each component name does not contain '/', the function will automatically add it. 2. If a component is an absolute path, all components before it will be discarded. 3. If the last component is empty, the generated path ends with a '/' separator
  • os.path.walk(path, visit, arg) # traverses the path and calls the visit function when entering each directory. The visit function must have three parameters (arg, dirname, names). Dirname represents the directory name of the current directory, names represents all file names in the current directory, and args is the third parameter of walk
  • os.chdir(path) # changes the current working directory to the specified path.

6. Execute command class

  • os.close(fd) # closes the specified file descriptor fd
  • os.system() # run shell command

1, File operation class

os.remove(path)

Function: used to delete files in the specified path. If the specified path is a directory, an OSError is thrown.

os.remove('C:/Users/zhengxiang.wzx/Desktop/timg.jpg')

os.rename(src, dst)

Function: name files or directories, and rename corresponding files

  • src – the name of the directory to modify
  • dst – modified directory name
os.rename("Picture download.py","Picture download 1.py")

os.renames(old, new)

Function:

  • old – directory to rename
  • New -- the new name of the file or directory. It can even be a file contained in a directory, or a complete directory tree.
#While modifying the file name, the parent directory can also be changed
os.renames("test/Python 63 Detailed explanation of built-in functions.py","test2/Detailed explanation of built-in functions.py")

os.path.getmtime(path)

Function: returns the most recent file modification time, the number of seconds from the new era to the time of access.

os.path.getmtime('C:/Users/wuzhengxiang/Desktop/Stock data analysis/pi.txt')

1583069050.8148942

os.path.getctime(path)

Function: returns the creation time of the file path, and the number of seconds from the new era to the access time.

os.path.getctime('C:/Users/wuzhengxiang/Desktop/Stock data analysis/pi.txt')

1581868007.6123319

os.path.getsize(path)

Function: returns the file size. If the file does not exist, it returns an error (B bytes in size)

os.path.getsize('C:/Users/wuzhengxiang/Desktop/Stock data analysis/test.gif')

1128677

2. Directory operation class

os.mkdir(path[, mode])

Function: create directory in digital permission mode. The default mode is 0777 (octal).

#Create a new item 2233

os.mkdir('C:/Users/wuzhengxiang/Desktop/Stock data analysis/2233', mode=0777 )

os.makedirs(path, mode=0o777)

Function: create multi-level directory (such as' F:\XXX\SSS'), create XXX directory under disk F, and continue to create SSS directory under XXX directory

import os
os.makedirs("yiji/erji")

os.rmdir(path) (the first level directory is required to be empty)

Function: # delete the path directory (only the first level directory can be deleted, such as' F:\XXX\SSS'), delete only the SSS directory, and the directory must be empty

import os
os.rmdir("yiji")

OS. Removediers (path) (multi level directory is required to be empty)

Function: # delete multi-level directories (such as' F:\XXX\SSS'), which must be empty. Delete SSS and FFF directories, which must be empty

import os
os.removedirs("yiji/erji")

3. Judgment

os.path.isfile(path)

Function: judge whether the path is a file

os.path.isfile("C:/Users/wuzhengxiang/Desktop/Stock data analysis/pi.txt")

True#Not a file returned False

s.path.isfile("C:/Users/wuzhengxiang/Desktop/Stock data analysis/")

False

os.path.isdir(path)

Function: judge whether the path is a directory

os.path.isdir('C:/Users/wuzhengxiang/Desktop/Stock data analysis')

True

os.path.isdir('C:/Users/wuzhengxiang/Desktop/Stock data analysis/pi.txt')

False

os.path.exists(path)

Function: returns True if the path path exists; Returns False if the path does not exist.

os.path.exists('C:/Users/wuzhengxiang/Desktop/Stock data analysis/')

True

os.path.exists('C:/Users/wuzhengxiang/Desktop/Stock data analysis/pi_01.txt')

False

os.path.isabs(path)

Function: judge whether it is an absolute path, that is, in the WIndow system, if the input string starts with "/", os.path.isabs() will return True

os.path.isabs('D:/thunder')

True

os.path.isabs('D:\thunder')

False

4. Environment variable query / acquisition class

os.name()

Function: displays the currently used platform, 'nt' for Windows and 'posix' for Linux

os.name

'nt'

os.stat(path)

Function: obtain file or directory information

os.stat('C:/Users/wuzhengxiang/Desktop/Stock data analysis\\pi.txt')

os.stat_result(st_mode=33206, st_ino=22236523160361562, st_dev=2419217970, st_nlink=1

, st_uid=0, st_gid=0, st_size=53, st_atime=1589638199, st_mtime=1589638199, st_ctime=1581868007)

5. Address / path class

os.getcwd()

Function: return the working directory of the current process.

import os
print(os.getcwd())

#C:\Users\Administrator\Desktop \ test

os.path.abspath(path)

Function: return the absolute path of the file

import os
print(os.path.abspath("pandas.py"))

# C:\Users\Administrator\Desktop \ test \ pandas.py

os.listdir(path)

Function: list all files and folders in the directory

os.listdir('.')

['ETF Research.py', 'foo.txt', 'pi.txt', 'render.html']

os.path.basename(path)

Function: return file name, pure string processing logic, and path error

os.path.basename('C:\\Users\\zhengxiang.wzx\\all_data.xlsx')

'all_data.xlsx'

os.path.dirname(path)

Function: return file path

os.path.dirname('C://python//my_file.txt')

'C://python'

os.path.split(path)

Function: divide the path into dirname and basename, and return a tuple

os.path.split('D:\Python\test\data.txt')

('D:\\Python\test', 'data.txt')

os.path.splitext(path)

Function: split path and return tuple of path name and file extension

os.path.splitext('C:/Users/zhengxiang.wzx/IMG_7358.JPG')

('C:/Users/zhengxiang.wzx/IMG_7358', '.JPG')

os.walk(path, visit, arg)

Function: traverse the path and call the visit function when entering each directory. The visit function must have three parameters (arg, dirname, names). Dirname represents the directory name of the current directory, names represents all file names in the current directory, and args is the third parameter of walk

import os
print(list(os.walk("data/")))


[('data/', ['ceshi1'], ['1-1.txt', '1.txt', '1_empty.txt', '2.txt', '2.txt.zip', '3.txt', '4.txt', 'Personnel information of branch construction and maintenance department.xlsx', 'driver's license.jpg']), ('data/ceshi1', ['111', 'ceshi1'], ['1-1.txt', '1-2.txt', '1.txt', '1_empty.txt', '2.txt', '2.txt.zip', '3.txt', '4.txt', 'Personnel information of branch construction and maintenance department.xlsx', 'driver's license.jpg']), ('data/ceshi1\\111', [], []), ('data/ceshi1\\ceshi1', ['111'], ['1-2.txt']), ('data/ceshi1\\ceshi1\\111', [], [])]
[Finished in 0.2s]

os.chdir(path)

Function: change the current working directory to the specified path.

#View the current directory os.getcwd()

'C:\\Users\\wuzhengxiang'#Reset current workspace

os.chdir('C:/Users/wuzhengxiang/Desktop/Stock data analysis')

#Check the current directory again. It has become a new directory

os.getcwd()

'C:\\Users\\wuzhengxiang\\Desktop\\Stock data analysis'

6. Execute command class

os.close(fd) (used when reading and writing files, but if you use the with form when reading files, you don't need to set the close function)

Function: close the specified file descriptor fd

fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

os.write(fd, bytes("This is test", encoding = "utf8"))

os.close( fd )

os.system()

Function: run shell command

>>>os.system('cmd')  #Open terminal under Windows
>>>os.system('ls')  #View all files in the current directory under Linux

Note: when running the shell command here, if you want to call the variables before python, you can use the following method:

var=123
os.environ['var']=str(var) //Note that "string" is in [] here
os.system('echo $var')

Topics: Python Back-end