前言
使用Python经常会遇到与文件处理相关的问题,与文件相关的操作自然离不开文件路径的处理。在Python的os.path模块中提供了一些与文件路径处理相关的函数。
os.path.split()
返回文件的路径和文件名,返回的文件名与使用basename()
返回的文件名一样。
dirname,filename=os.path.split('/home/ubuntu/python_coding/split_func/split_function.py')
print (dirname)
print (filename) #输出为:
输出为:
/home/ubuntu/python_coding/split_func
split_function.py
>>> dir,name = os.path.split('/home/ubuntu/python_coding/split_func/')
>>>> print(dir)
/home/ubuntu/python_coding/split_func
>>> print(name) #空字符串
>>> dir,name = os.path.split('/home/ubuntu/python_coding/split_func')
>>> print(dir)
/home/ubuntu/python_coding
>>> print(name)
split_func
os.path.join()
拼接路径。
import os
filename=os.path.join('/home/ubuntu/python_coding','split_func')
print (filename) #输出为:/home/ubuntu/python_coding/split_func
os.path.splitext()
os.path.splitext(“文件路径”) 分离文件名与扩展名;默认返回(fname,fextension)元组,可做分片操作。
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.basename()
os.path.basename(),返回path最后的文件名。若path以/或\结尾,那么就会返回空值。
path='D:\优快云'
os.path.basename(path) #返回优快云
os.walk()
用于遍历文件夹,当文件夹的层级比较多,并且未知时比较方便。
示例代码如下:
import os
root = 'F:/competition/嵌入式设备使用_032'
for i in os.walk(root):
print(i)
print('--------------------------------------')
for root_dir, sub_dirs, files in os.walk(root):
print(root_dir)
print(sub_dirs)
print(files)
print('--------------------------------------')
可以看到我们只需要拼接,在循环中拼接root和files中的内容就可以遍历所有的文件。
参考文章: