本文介绍os模块获取路径方法
首先我们需要导入os模块
代码如下:
#os模块
import os
#os.getcwd()获取当前路径
current_path = os.getcwd()
print(current_path)
#os.path.abspath(name)获取绝对路径,name可以是文件名或目录
my_path = os.path.abspath('test.ini')
print(my_path)
#os.path.realpath(__file__)获取当前绝对路径
AP = os.path.realpath(__file__)
print(AP)
#os.path.split(path)剪切路径跟文件名
print(os.path.split(os.path.realpath(__file__))[0]) #当前路径
print(os.path.split(os.path.realpath(__file__))[1]) #当前文件名
#os.path.basename(path)返回文件名或目录名,path为路径或绝对路径
dir_file = os.path.basename(my_path)
print(dir_file)
#os.path.dirname(path)返回文件路径,path为路径或绝对路径
path = os.path.dirname(my_path)
print(path)
#os.path.getsize(name)返回文件大小,目录返回OL,其中name可以是文件名或目录
size = os.path.getsize('test.ini)
print(size)
#os.path.join(path, name)拼接目录与文件名或目录,其中name可以是文件名或目录
new_path = os.path.join(current_path, 'test.ini')
print(new_path)
#判断
#判断文件或目录是否存在,存在返回true,否则返回false
os.path.exists(path)
#判断是否为文件,是返回true,否则返回false
os.path.isfile(path)
#判断是都为目录,是返回true,否则返回false
os.path.isdir(path)
根据上面的介绍的方法我们写个程序,输入一个路径,判断该路径是否存在,是否为文件,文件大小多少
def file_size():
file_path = input('请输入文件路径:')
if os.path.exists(file_path) == True: #判断路径是否存在
if os.path.isfile(file_path) == True: #判断路径是否文件路径
dir = os.path.basename(file_path) #获取路径文件名
size = os.path.getsize(file_path) #获取文件大小
print('%s文件的大小是:%d' % (dir, size))
else:
print('该路径为目录,不是文件路径!')
file_size() #递归
else:
print('该路径错误!')
file_size() #递归
执行结果如下:
请输入文件路径:D:\不存在的路径
该路径错误!
请输入文件路径:D:\目录
该路径为目录,不是文件路径!
请输入文件路径:D:\pytest.pdf
pytest.pdf文件的大小是:776195
再次封装一个获取当前目录下指定后缀文件名。
代码如下:
def get_dir_name(suffix):
"""
获取当前目录下指定后缀文件名
:param suffix: 后缀名。如:".txt"
:return: 返回后缀名相同的文件名
"""
for root, dirs, files in os.walk("./"):
for d in files: # 循环获取当前目录下所有文件名
# print(d)
if os.path.splitext(d)[1] == suffix: # 匹配后缀相同的文件名
# print(d)
return d
get_dir_name('.txt')