文件操作

一、Open创建文件读写

file = open(filename[,mode,encoding])
• mode:
 “r” |“w”
 “a” 追加;文件不存在->创建,指针在文件头 文件存在->末尾追加,指针在文件尾
 "b"二进制方式打开文件 “rb” “wb”
 “+” 读写方式打开文件 “a+”

file.read([size])
file.readline #只读一行
file.readlines() #读取所有内容,返回一个列表
file.write(str) #将str写入文件
file.writelines(s_list) #将s_list写入文件,不添加换行符
file.seek(offset[,whence]) # 移动文件指针
file.tell() #返回文件当前指针位置
file.flush() #缓冲区内容跟写入文件,但不关闭文件
file.close() # 关闭文件

二、with语句(上下文管理器)

自动管理上下文资源,跳出with语句块就确包文件正确的关闭,达到释放资源的目的
with open(filename[,mode,encoding]) as src_file:
src_file.read()
离开时,自动调用__exti__()

"""
MyContentMgr实现了特殊方法__enter__(),__exit__() 称为该类对象遵守了上下文管理器协议
该类的实例对象,称为上下文管理器
MyContentMgr的实例对象调用方法是 自动调用__enter__(),__exit__()两个函数
"""
class MyContentMgr(object):
    def __enter__(self):
        print("enter方法被调用执行...")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit方法被调用执行...")

    def show(self):
        print("show方法被调用执行...")


with MyContentMgr() as file:
    file.show()


enter方法被调用执行...
show方法被调用执行...
exit方法被调用执行...

三、复制图片文件

src_file = open('logo.png','rb')
target_file = open('copy_logo.png',"wb")
target_file.write(src_file.read())
src_file.close()
target_file.close()
with open('logo.png',"rb") as src_file:
    with open('copy_logo.png',"wb") as target_file:
        target_file.write(src_file.read())

目录操作 OS模块

一、操作系统相关命令

1、 os.system() 命令行

import os
os.system('notepad.exe')
os.system('calc.exe')

2、os.startfile() 直接调用可执行文件

import os
os.startfile(路径)
#注意\要写成转义字符\\

二、操作目录相关函数

1、os.getcwd() 返回当前工作目录

import os
print(os.getcwd())


D:\Course_Python\machine_learning\machine_basic

2、os.listdir(path) 返回指定路径下的文件和目录信息

import os
lst=os.listdir(os.getcwd())
print(lst)


['Bayes.py', 'character_extraction.py', 'data_preprocession.py', 'dating.txt', 'demo.py', 'iris_tree.dot', 'KNN_Iris.py', 'linear.py', 'my_ridge.pkl', 'titanic_demo.ipynb', 'titanic_tree.dot', 'Tree_Iris.py']

3、os.mkdir(path[,mode])                       在当前目录下创建目录
4、os.mkdirs(path1/path2/path3)           在当前目录下创建多级目录
5、os.rmdir()                                          删除目录
6、os.removedirs(path1/path2/path3)   删除多级目录
7、os.chdir(path)                                   将path设置为当前工作目录

三、os.path模块操作目录相关函数

  1. abspath(path)          获取文件/目录的绝对路径
  2. exists(path)              判断文件/目录是否存在
  3. join(path,name)       将目录与目录或文件名拼接起来
  4. splitext()                    分离文件名和扩展名
  5. basename(path)      从一个目录中提取文件名
  6. dirname(path)          从一个路径中提取文件路径,不包括文件名
  7. isdir(path)                判断是否为路径

四、列出指定目录下的所有.py文件

1、文件夹内无文件夹

import os
path = os.getcwd()
lst = os.listdir(path)
for filename in lst:
    if filename.endswith('.py'):
        print(filename)

2、文件夹内嵌套文件夹
os.walk()递归遍历文件夹内.py文件

import os
path = os.getcwd()
lst_files = os.walk(path)
for dirpath,dirname,filename in lst_files:
    for dir in dirname:
        print(os.path.join(dirpath,dir))
    print('----------------------------')
    for file in filename:
        print(os.path.join(dirpath,file))
    print('----------------------------')