Python 文件操作与模块
读取
注意事项,如果文件打开之后,后面这个文件的所有操作都将会续接上次的位置
python
f = open("d:/Python/dataType/a.txt",'r',encoding='utf-8') #打开文件
print(f.read()) #读取文件内容 文件.read(num) num是读取多少字,不传是所有
print(f.readlines()) #读取所有行,返回一个列表,如果传入num是读取几行
line1 = f.readline() #读取一行
line2 = f.readline() #读取一行
for i in f: #遍历文件,一行一行
print(i)
f.close() #关闭文件
with open("d:/Python/dataType/a.txt","r",encoding="utf-8") as f: #with语句打开文件,自动关闭文件
for i in f:
print(i)
with open("d:/Python/dataType/a.txt", "r", encoding="utf-8") as f:
# 读取itheima出现的次数
line_count = 0
for line in f:
line = line.strip().split(" ")
for i in line:
if(i == 'itheima'):
line_count += 1
print(line_count)f = open("d:/Python/dataType/a.txt",'r',encoding='utf-8') #打开文件
print(f.read()) #读取文件内容 文件.read(num) num是读取多少字,不传是所有
print(f.readlines()) #读取所有行,返回一个列表,如果传入num是读取几行
line1 = f.readline() #读取一行
line2 = f.readline() #读取一行
for i in f: #遍历文件,一行一行
print(i)
f.close() #关闭文件
with open("d:/Python/dataType/a.txt","r",encoding="utf-8") as f: #with语句打开文件,自动关闭文件
for i in f:
print(i)
with open("d:/Python/dataType/a.txt", "r", encoding="utf-8") as f:
# 读取itheima出现的次数
line_count = 0
for line in f:
line = line.strip().split(" ")
for i in line:
if(i == 'itheima'):
line_count += 1
print(line_count)写入
直接调用 write,内容并未真正写入文件,而是会积攒在程序的内存中,称之为缓冲区
当调用 flush 的时候,内容会真正写入文件
close()方法,附带 flush()方法的功能
这样做是避免频繁的操作硬盘,导致效率下降(攒一堆,一次性写磁盘)
- 使用
w模式,每次写入会将原有内容清空,写入新内容 - 使用
a模式,文件不存在会创建文件,文件存在会在最后追加内容写入文件
python
with open("d:/Python/dataType/a.txt", "w", encoding="utf-8") as f:
f.write("你好") # 写入
f.flush() # 刷新with open("d:/Python/dataType/a.txt", "w", encoding="utf-8") as f:
f.write("你好") # 写入
f.flush() # 刷新pathlib(推荐)
Python 3.4+ 引入的面向对象文件路径操作库,推荐替代 os.path:
python
from pathlib import Path
# 路径创建
p = Path("d:/Python/dataType")
home = Path.home() # 用户目录
cwd = Path.cwd() # 当前工作目录
# 路径操作
p = Path("data") / "subdir" / "file.txt" # 拼接
print(p.suffix) # .txt
print(p.stem) # file
print(p.name) # file.txt
print(p.parent) # data/subdir
print(p.parents) # 所有父级目录
# 文件操作
path = Path("example.txt")
path.write_text("Hello, World!", encoding="utf-8") # 写入文本
content = path.read_text(encoding="utf-8") # 读取文本
path.write_bytes(b"binary data") # 写入二进制
data = path.read_bytes() # 读取二进制
# 目录遍历
for f in Path(".").iterdir(): # 当前目录
print(f)
for f in Path(".").glob("*.py"): # 匹配 .py 文件
print(f)
for f in Path(".").rglob("**/*"): # 递归遍历所有
print(f)
# 文件信息
print(path.exists()) # 是否存在
print(path.is_file()) # 是否是文件
print(path.is_dir()) # 是否是目录
print(path.stat().size) # 文件大小
# 创建/删除
Path("new_dir").mkdir(parents=True, exist_ok=True) # 创建目录
Path("empty.txt").touch() # 创建空文件
Path("temp.txt").unlink(missing_ok=True) # 删除文件
Path("old_dir").rmdir() # 删除空目录
# 对比 os.path
# 旧方式: os.path.join(os.path.dirname(__file__), "data", "file.txt")
# 新方式: Path(__file__).parent / "data" / "file.txt"from pathlib import Path
# 路径创建
p = Path("d:/Python/dataType")
home = Path.home() # 用户目录
cwd = Path.cwd() # 当前工作目录
# 路径操作
p = Path("data") / "subdir" / "file.txt" # 拼接
print(p.suffix) # .txt
print(p.stem) # file
print(p.name) # file.txt
print(p.parent) # data/subdir
print(p.parents) # 所有父级目录
# 文件操作
path = Path("example.txt")
path.write_text("Hello, World!", encoding="utf-8") # 写入文本
content = path.read_text(encoding="utf-8") # 读取文本
path.write_bytes(b"binary data") # 写入二进制
data = path.read_bytes() # 读取二进制
# 目录遍历
for f in Path(".").iterdir(): # 当前目录
print(f)
for f in Path(".").glob("*.py"): # 匹配 .py 文件
print(f)
for f in Path(".").rglob("**/*"): # 递归遍历所有
print(f)
# 文件信息
print(path.exists()) # 是否存在
print(path.is_file()) # 是否是文件
print(path.is_dir()) # 是否是目录
print(path.stat().size) # 文件大小
# 创建/删除
Path("new_dir").mkdir(parents=True, exist_ok=True) # 创建目录
Path("empty.txt").touch() # 创建空文件
Path("temp.txt").unlink(missing_ok=True) # 删除文件
Path("old_dir").rmdir() # 删除空目录
# 对比 os.path
# 旧方式: os.path.join(os.path.dirname(__file__), "data", "file.txt")
# 新方式: Path(__file__).parent / "data" / "file.txt"模块
模块的导入
from 可以省略,直接 import
as 别名可以省略
通过”.”来调用模块提供的功能
模块的导入一般写在代码文件的开头位置
常用的组合形式如:
import 模块名
python# 导入 import 模块名 import 模块名1,模块名2 # 使用 模块名.功能名()# 导入 import 模块名 import 模块名1,模块名2 # 使用 模块名.功能名()from 模块名 import 类、变量、方法等
python# 导入 from 模块名 import 功能名 # 使用 功能名()# 导入 from 模块名 import 功能名 # 使用 功能名()from 模块名 import *
# 导入 from 模块名 import * # 使用 功能名()# 导入 from 模块名 import * # 使用 功能名()import 模块名 as 别名
python# 导入一:模块定义别名 import 模块名 as 别名 # 使用一: 别名.功能名()# 导入一:模块定义别名 import 模块名 as 别名 # 使用一: 别名.功能名()from 模块名 import 功能名 as 别名
# 导入二:功能定义别名 from 模块名 import 功能 as 别名 # 使用二: 别名()# 导入二:功能定义别名 from 模块名 import 功能 as 别名 # 使用二: 别名()
包
自定义包
创建包,文件
- 导入包与导入模块几种方式类似,例如:
python
import 包名.模块名
包名.模块名.功能名()import 包名.模块名
包名.模块名.功能名()限制导入
- 可以在
__init__.py文件中添加__all__ = ['模块名'],控制允许导入的模块列表 - 与导入模块类似
__all__只针对from 包名.模块名 import *而对其他方式无效
Cao Note