温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中os模块最常用的方法是怎样的

发布时间:2021-10-11 17:45:24 阅读:186 作者:柒染 栏目:大数据
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

本篇文章为大家展示了Python中os模块最常用的方法是怎样的,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

最近在搞天池的AI医疗那个比赛,所以没时间写文章了,有没有小伙伴想一起做的,可以找我私聊!

***********print("分割线")***********

为什么是最最常用的呢,这里是我通过总结大神们的代码,经常被使用的方法,也是在实际工程中,有助于提高效率的必然会使用的方法。我写的所有文章,都是为机器学习服务的,这里不考虑web开发,及其他Python开发工程中使用的方法。

# coding:utf-8import os# 总结一下os模块中最最常用的方法,""">>> import os>>> print(len(dir(os)))149# os模块非常强大,功能很多很多,今天总结一下,# 我都用过哪些方法,其实相比于全部的方法,常用# 的不超过20种,或者10种?"""""# 1. os.getcwd()可以查看当前程序的工作目录。""">>> os.getcwd()'C:\\Python27'# 2. os.path.exists 确定路径是否存在,返回值为# 布尔类型。>>> new_path = "F:/test_path">>> print(os.path.exists("F:/test_path"))False# 3. 如果不存在,我们可以使用os.makedirs()来建# 立文件目录。>>> if not os.path.exists(new_path):        os.makedirs(new_path)# os中另外一个建立文件夹的函数是os.mkdirs(),# 它俩的区别是,os.makedirs() 可以递归的建立# 文件夹,也就是可以创建多级目录,而os.mkdirs()# 只能创建一级目录。# 举个栗子>>> new_path = "F:/test_path_1/test_path_1">>> if not os.path.exists(new_path):   os.mkdir(new_path)# WindowsError,系统错误。Traceback (most recent call last):  File "<pyshell#9>", line 2, in <module>    os.mkdir("F:/test_path_1/test_path_1")WindowsError: [Error 3] : 'F:/test_path_1/test_path_1'""""""# 4. os.path.join, 链接两个的路径>>> path2 = "F:/test_path2/">>> path3 = "second_path">>> path2_and_path3 = os.path.join(path2, path3)>>> path2_and_path3'F:/test_path2/second_path'# 再举个栗子,在深度学习里面,我们经常会把文件路# 径和文件名做链接,并且会把结果文件放到一个新的# 文件夹下,对于这个简单的问题,就可以# 这样来做。data_dir = "F:/data_dir/train/"files_name = "*.jpg"results_dir = "F:/data_dir/results/"all_data_dirs = os.path.join(data_dir, files_name)all_results_dirs = os.path.join(results_dir, files_name)if not os.path.exists(all_results_dirs):    os.makedirs(all_results_dirs)""""""# 5. os.path.basename返回文件路径的最后一层文件名。>>> path2 = "F:/test_path2/">>> path3 = "second_path">>> path2_and_path3 = os.path.join(path2, path3)>>> path2_and_path3'F:/test_path2/second_path'>>> os.path.basename(path2_and_path3)'second_path'>>> os.path.basename(os.path.join(path2_and_path3, "001.jpg"))'001.jpg'""""""# 5. os.listdir() 列出当前目录下所有文件和文件夹>>> path_3 = "F:/test_path/test_path_1">>> os.listdir(path_3)['mini_df_10.csv', 'mini_df_3.csv', 'mini_df_4.csv', 'mini_df_5.csv','mini_df_6.csv', 'mini_df_7.csv', 'mini_df_8.csv', 'mini_df_9.csv']# 我们新建一个文件夹。>>> path_3 = "F:/test_path/test_path_1">>> print(os.listdir(path_3))['mini_df_10.csv', 'mini_df_3.csv', 'mini_df_4.csv', 'mini_df_5.csv', 'mini_df_6.csv', 'mini_df_7.csv',  'mini_df_8.csv', 'mini_df_9.csv', '新建文件夹']"""

上述内容就是Python中os模块最常用的方法是怎样的,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:https://my.oschina.net/alvinpy/blog/4392280

AI

开发者交流群×