Python 学习 第二册 第11章 文件

----用教授的方式学习

目录

[11.1 打开文件](#11.1 打开文件)

[11.2 文件的基本方法](#11.2 文件的基本方法)

[11.2.1 读取和写入](#11.2.1 读取和写入)

[11.2.2 使用管道重定向输出](#11.2.2 使用管道重定向输出)

[11.2.3 读取和写入行](#11.2.3 读取和写入行)

[11.2.4 关闭文件](#11.2.4 关闭文件)

[11.3 迭代文件内容](#11.3 迭代文件内容)

[11.3.1 每次一个字符(或字节)](#11.3.1 每次一个字符(或字节))

[11.3.2 每次一行](#11.3.2 每次一行)

[11.3.3 读取所有内容](#11.3.3 读取所有内容)

[11.3.4 使用 fileinput 实现延迟行迭代](#11.3.4 使用 fileinput 实现延迟行迭代)

[11.3.5 文件迭代器](#11.3.5 文件迭代器)


11.1 打开文件

要打开文件,可使用函数open,它位于自动导入的模块io中。则可像下面这样打开它:

python 复制代码
>>> f = open('somefile.txt')

函数open的参数mode的可能取值有多个,如下:

|-----|---------------------|
| 值 | 描 述 |
| 'r' | 读取模式(默认值) |
| 'w' | 写入模式 |
| 'x' | 独占写入模式 |
| 'a' | 附加模式 |
| 'b' | 二进制模式(与其他模式结合使用) |
| 't' | 文本模式(默认值,与其他模式结合使用) |
| '+' | 读写模式(与其他模式结合使用) |

11.2 文件的基本方法

11.2.1 读取和写入

可使用f.write来写入数据,还可使用f.read来读取数据。

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| >>> f = open('somefile.txt', 'w') >>> f.write('Hello, ') 7 >>> f.write('World!') 6 >>> f.close() >>> f = open('somefile.txt', 'r') >>> f.read(4) 'Hell' >>> f.read() 'o, World!' |

11.2.2 使用管道重定向输出

在bash等shell中,可依次输入多个命令,并使用管道将它们链接起来,如下所示:

$ cat somefile.txt | python somescript.py | sort

python 复制代码
# somescript.py 
import sys 
text = sys.stdin.read() 
words = text.split() 
wordcount = len(words) 
print('Wordcount:', wordcount) 

11.2.3 读取和写入行

要读取一行(从当前位置到下一个分行符的文本),可使用方法readline。

如:some_file. readline()返回的是'Hello, World!\n'。

11.2.4 关闭文件

调用方法close将文件关闭。

python 复制代码
# 在这里打开文件
try: 
    # 将数据写入到文件中
finally: 
    file.close()

11.3 迭代文件内容

本节的所有示例中,我都将使用一个名为process的虚构函数来表示对每个字符或行所做的处理,你可以用自己的喜欢的方式实现这个函数。

python 复制代码
def process(string): 
    print('Processing:', string)

11.3.1 每次一个字符(或字节)

python 复制代码
with open(filename) as f: 
    char = f.read(1) 
    while char: 
        process(char) 
        char = f.read(1)

以不同的方式编写循环

python 复制代码
with open(filename) as f: 
     while True:
        char = f.read(1) 
        if not char: break 
        process(char)

11.3.2 每次一行

python 复制代码
with open(filename) as f: 
    while True: 
        line = f.readline() 
        if not line: break 
        process(line)

11.3.3 读取所有内容

使用read迭代字符

python 复制代码
with open(filename) as f: 
     for char in f.read(): 
         process(char)

使用readlines迭代行

python 复制代码
with open(filename) as f: 
     for line in f.readlines(): 
         process(line)

11.3.4 使用 fileinput 实现延迟行迭代

使用fileinput迭代行

python 复制代码
import fileinput 
     for line in fileinput.input(filename): 
         process(line)

11.3.5 文件迭代器

迭代文件

python 复制代码
with open(filename) as f: 
    for line in f: 
      process(line)

sys.stdin也是可迭代的,因此要迭代标准输入中的所有行,可像下面这样做:

python 复制代码
import sys 
    for line in sys.stdin: 
        process(line)

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| >>> f = open('somefile.txt', 'w') >>> print('First', 'line', file=f) >>> print('Second', 'line', file=f) >>> print('Third', 'and final', 'line', file=f) >>> f.close() >>> lines = list(open('somefile.txt')) >>> lines ['First line\n', 'Second line\n', 'Third and final line\n'] >>> first, second, third = open('somefile.txt') >>> first 'First line\n' >>> second 'Second line\n' >>> third 'Third and final line\n' |

---end

相关推荐
花酒锄作田5 小时前
[MCP][01]简介与概念
python·llm·mcp
Python私教5 小时前
Django全栈班v1.04 Python基础语法 20250912 上午
后端·python·django
言之。5 小时前
Django REST框架:ModelViewSet全面解析
数据库·python·django
Pocker_Spades_A5 小时前
Python快速入门专业版(二十六):Python函数基础:定义、调用与返回值(Hello函数案例)
开发语言·python
island13145 小时前
【C++框架#5】Elasticsearch 安装和使用
开发语言·c++·elasticsearch
周周记笔记6 小时前
学习笔记:Python的起源
开发语言·python
shizidushu6 小时前
Hugging Face NLP课程学习记录 - 3. 微调一个预训练模型
人工智能·学习·自然语言处理·微调·huggingface
懒大王95276 小时前
uni-app + Vue3 + EZUIKit.js 播放视频流
开发语言·javascript·uni-app
_extraordinary_6 小时前
Java 多线程进阶(四)-- 锁策略,CAS,synchronized的原理,JUC当中常见的类
java·开发语言
魂尾ac6 小时前
Django + Vue3 前后端分离技术实现自动化测试平台从零到有系列 <第一章> 之 注册登录实现
后端·python·django·vue