文件处理
文件处理
urcuteimmehinge定义
定义文件路径和文件名
1 | import os |
打开/关闭文件
读
open方式
1 | # 打开 open() |
with方式(文件管理器处理)
with open读写文件不需要手动close。
1 | with open(file_path, 'r') as f: |
逐行读取
1 | with open(file_path, 'r') as f: |
可控读取字符(每次读取100个字符)
1 | with open(file_path, 'r') as f: |
写
增加内容
1 | with open(file_path, 'a') as f: |
编写内容
1 | with open('./text.txt', 'w') as f: |
1 | with open('test.txt', 'w') as f: |
迭代器
1 | class LineIterator: |
生成器
1 | def line_generator(file_path): |
例子
读取test.txt文档,并把它复制到新建的test2.txt文档。
1 | with open(file_path, 'r') as rf: |
1 | with open(file_path, 'r') as rf: |
复制IMG
1 | # xb 二进制读写 |
斐波拉契数列
1 | def fib_generator(): |
内存使用情况
1 | import tracemalloc |
1 |
评论
匿名评论隐私政策
✅ 你无需删除空行,直接评论以获取最佳展示效果