一、Python中不要求对象必须实现某个特定的类,只要该对象含有某一方法如read()方法,该对象可以是内存的字节流,网络流,自定义流等,这种思想称为File-like-Object。
with open('filepath','rb',encoding='gbk',errors='ignore') as f:
print(f.read())
Python中提供了with语句自动调用close方法,使用with语句操作IO文件,数据更安全高效。
二、数据读取操作的对象不一定是文件,可以在内存中进行读写操作,StringIO和BytesIO就是直接在内存中读写字符串和二进制数据的。。
1、StringIO就是在内存中读写str,StringIO的操作方法和open函数是一致的。
要将str写入StringIO,首先需要创建一个StringIO

2、BytesIO实现了在内存中读写bytes,首先创建一个BytesIO,然后进行读写:


三、操作文件和目录
Python内置的os模块可以直接调用操作系统提供的接口函数来操作文件和目录


找出指定目录及其子目录下包含指定字符串的文件,打印目录路径

网友评论