[编程经验]Python中os模块最最常用的方法

时间:2022-05-08
本文章向大家介绍[编程经验]Python中os模块最最常用的方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

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

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

# coding:utf-8
import 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, 链接两个的路径
>>> path1 = "F:/test_path1/"
>>> path2 = "second_path"
>>> path1_and_path2 = os.path.join(path1, path2)
>>> path1_and_path2
'F:/test_path1/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返回文件路径的最后一层文件名。
>>> path1 = "F:/test_path1/"
>>> path2 = "second_path"
>>> path1_and_path2 = os.path.join(path1, path2)
>>> path1_and_path2
'F:/test_path1/second_path'
>>> os.path.basename(path1_and_path2)
'second_path'
>>> os.path.basename(os.path.join(path1_and_path2, "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', '新建文件夹']
"""

本文为作者原创,如有雷同,必然是别人抄我的。