Python day 10-Commonly used functions of files/directories in OS modules

Commonly used functions of files/directories in OS modules

The commonly used operating systems we know are: Windows, Mac OS, Linu, Unix, etc. The underlying operating principles of these operating systems are different for file system access, so you may have to consider which files to use for different systems. System module... This approach is very unfriendly and troublesome, because it means that when your program's operating environment changes, you have to modify a lot of code accordingly.
With the OS (Operation System) module, we don't need to care about which module is used under which operating system, the OS module will help you select the correct module and call it.

  1. os.getcwd() is used to return the current working directory.
  2. os.chdir(path) is used to change the current working directory to the specified path.
import os
path = 'C:\\'
print("当前工作目录 : %s" % os.getcwd())
# 当前工作目录 : C:\Users\Administrator\PycharmProjects\untitled1
os.chdir(path)
print("目录修改成功 : %s" % os.getcwd())
# 目录修改成功 : C:\
  1. listdir (path='.') returns a list of the names of files or folders contained in the folder specified by path.
import os
dirs = os.listdir()
for item in dirs:
    print(item)
  1. os.mkdir(path) creates a single-level directory, and throws an exception if the directory already exists.
import os

if os.path.isdir(r'.\b') is False:
    os.mkdir(r'.\B')
    os.mkdir(r'.\B\A')
    
os.mkdir(r'.\C\A') # FileNotFoundError

Did not understand the above

  1. os.makedirs(path) is used to recursively create multi-level directories. If the directory already exists, an exception will be thrown.
import os
os.makedirs(r'.\E\A')
  1. os.remove(path) is used to delete files in the specified path. If the specified path is a directory, OSError will be thrown.
    [Example] First create the .\E\A\text.txt file, and then delete it.
import os
print("目录为: %s" % os.listdir(r'.\E\A'))
os.remove(r'.\E\A\test.txt')
print("目录为: %s" % os.listdir(r'.\E\A'))
  1. os.rmdir(path) is used to delete a single-level directory. Only if this folder is empty, otherwise, OSError will be thrown.
    [Example] First create the .\E\A directory, and then delete it.
import os

print("目录为: %s" % os.listdir(r'.\E'))
os.rmdir(r'.\E\A')
print("目录为: %s" % os.listdir(r'.\E'))

Add r before the letter to indicate raw string, also called raw string constant.

  1. os.removedirs(path) Recursively delete a directory, try to delete it layer by layer from the subdirectory to the parent directory, and throw an exception when the directory is not empty.
    [Example] First create the .\E\A directory, and then delete it.
import os

print("目录为: %s" % os.listdir(os.getcwd()))
os.removedirs(r'.\E\A') # 先删除A 然后删除E
print("目录为: %s" % os.listdir(os.getcwd()))
  1. The os.rename(src, dst) method is used to name files or directories, from src to dst. If dst is an existing directory, OSError will be thrown.
    [Example] Rename the test.txt file to test2.txt.
import os

print("目录为: %s" % os.listdir(os.getcwd()))
os.rename("test.txt", "test2.txt")
print("重命名成功。")
print("目录为: %s" % os.listdir(os.getcwd()))
  1. os.system(command) Run the shell command of the system (convert a string into a command)

[Example] First create an a.py file by yourself, and then open it by the shell command.

import os
path = os.getcwd() + '\\a.py'
a = os.system(r'python %s' % path)
os.system('calc') # 打开计算器
  1. os.curdir refers to the current directory (.)
  2. os.pardir refers to the upper level directory (…)
  3. os.sep output operating system specific path separator (\ under win, / under Linux)
  4. os.linesep The line terminator used by the current platform (\r\n under win, \n under Linux)
  5. os.name refers to the currently used operating system (including:'mac','nt')
import os
print(os.curdir) # .
print(os.pardir) # ..
print(os.sep) # \
print(os.linesep)
print(os.name) # nt
  1. os.path.basename(path) Remove the directory path and return the file name separately
  2. os.path.dirname(path) Remove the file name and return the directory path separately
  3. os.path.join(path1[, path2[, …]]) Combine each part of path1 and path2 into a path name
  4. os.path.split(path) splits the file name and path and returns a tuple of (f_path, f_name). If the directory is used completely, it will separate the last directory as the file name, and will not determine whether the file or directory exists.
  5. os.path.splitext(path) separates the file name and extension, and returns the (f_path, f_name) tuple.
import os
# 返回文件名
print(os.path.basename(r'C:\test\lsgo.txt')) # lsgo.txt
# 返回目录路径
print(os.path.dirname(r'C:\test\lsgo.txt')) # C:\test
# 将目录和文件名合成一个路径
print(os.path.join('C:\\', 'test', 'lsgo.txt')) # C:\test\lsgo.txt
# 分割文件名与路径
print(os.path.split(r'C:\test\lsgo.txt')) # ('C:\\test', 'lsgo.txt')
# 分离文件名与扩展名
print(os.path.splitext(r'C:\test\lsgo.txt')) # ('C:\\test\\lsgo', '.txt')
  1. os.path.getsize(file) returns the size of the specified file in bytes.
  2. os.path.getatime(file) returns the most recent access time of the specified file
  3. os.path.getctime(file) returns the creation time of the specified file
  4. os.path.getmtime(file) returns the latest modification time of the specified file
  5. Floating-point seconds, which can be converted by the gmtime() or localtime() function of the time module
import os
import time
file = r'.\lsgo.txt'
print(os.path.getsize(file)) # 30
print(os.path.getatime(file)) # 1565593737.347196
print(os.path.getctime(file)) # 1565593737.347196
print(os.path.getmtime(file)) # 1565593797.9298275
print(time.gmtime(os.path.getctime(file)))
# time.struct_time(tm_year=2019, tm_mon=8, tm_mday=12, tm_hour=7, tm_min=8, tm_sec=57, tm_wday=0,
tm_yday=224, tm_isdst=0)
print(time.localtime(os.path.getctime(file)))
# time.struct_time(tm_year=2019, tm_mon=8, tm_mday=12, tm_hour=15, tm_min=8, tm_sec=57, tm_wday=0,
tm_yday=224, tm_isdst=0)
  1. os.path.exists(path) Determine whether the specified path (directory or file) exists
  2. os.path.isabs(path) Determine whether the specified path is an absolute path
  3. os.path.isdir(path) Determine whether the specified path exists and is a directory
  4. os.path.isfile(path) Determine whether the specified path exists and is a file
  5. os.path.islink(path) Determine whether the specified path exists and is a symbolic link
  6. os.path.ismount(path) Determine whether the specified path exists and is a suspension point
  7. os.path.samefile(path1,path2) Determine whether the two paths of path1 and path2 point to the same file
import os
print(os.path.ismount('D:\\')) # True
print(os.path.ismount('D:\\Test')) # False

Didn't look closely

Guess you like

Origin blog.csdn.net/weixin_48760912/article/details/114744643