The python os file operation (commonly used than the whole, there are exemplified)

We compiled some frequently used, the operation command on the os

# 文件与文件路径操作
import os

os.path.join('usr', 'bin')  # 拼接文件路径
'usr\\bin'

os.getcwd()  # 获取当前所在的路径
'D:\\Py_Demo\\test_case'

os.chdir('d:\\AAA')  # 切换文件夹
os.getcwd()
'd:\\AAA'

os.makedirs('BBB')  # 创建文件夹
os.chdir('BBB')
os.getcwd()
'd:\\AAA\\BBB'

os.path.abspath('.')  # 获取文件的绝对路径
'D:\\Py_demo\\test_case'
os.path.abspath('.\\bak')
'D:\\Py_demo\\test_case\\bak'

os.path.isabs('.')  # 判断是否为绝对路径
False

os.path.realpath(path='', start='')  # 返回从start路径到path的相对路径字符串
os.path.relpath('D:\\Py_demo', 'D:\\Py_demo\\test_case\\bak')
'../..'
os.path.relpath('D:\\Py_demo\\test_case\\bak', 'D:\\Py_demo')
'test_case\\bak'

os.path.dirname('D:\\Py_demo\\testcase\\bak\\test.txt')  # 获取路径最后一个斜杠后的内容
'D:\\Py_demo\\testcase\\bak'

os.path.basename('D:\\Py_demo\\testcase\\bak\\test.txt')  # 获取路径最后一个斜杠后的内容
'test.txt'

os.path.split('D:\\Py_demo\\test_case\\bak\\test.txt')  # 拆分文件路径和文件名
('D:\\Py_demo\\test_case\\bak', 'test.txt')


import os
path_01 = "D:/User/wgy/workplace/data/notMNIST_large.tar.gar" 
path_02 ='D:/User/wgy/workplace/data/notMNIST_large'
root_01=os.path.splitext(path_01) #分离文件名与扩展名
root_02=os.path.splitext(path_02)
print(root_01)
print(root_02)

# 结果:
('D:/User/wgy/workplace/data/notMNIST_large.tar', '.gar')
('D:/User/wgy/workplace/data/notMNIST_large', '')

os.path.sep  # 返回当前系统文件路径的符号
'\\'
a = 'D:\Py_demo\\test_case\\bak\\test,txt'
a.split(os.path.sep)
['D:, Py demo', 'test case', 'bak', 'test.txt']

os.path.getsize('./') # 获取当前路径下文件大小
# 4096
os.getcwd()
'D:\Py_demo\\test_case'

os.listdir('./')  # 列出当前路径下的所有文件及文件夹
['idea','bak', 'bsselenium', 'selenuim_v1.0', 'selenium_v1.1']

os.path.exists('bak') #判断路径是否存在
True

os.path.isfile('bak')  # 判断是否为文件
False

os.path.isdir('bak') # 判斯是否为文件夹
# True
Published 20 original articles · won praise 30 · views 30000 +

Guess you like

Origin blog.csdn.net/ever_siyan/article/details/104507390