----用教授的方式学习
目录
11.1 打开文件
要打开文件,可使用函数open,它位于自动导入的模块io中。则可像下面这样打开它:
>>> 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
# 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将文件关闭。
# 在这里打开文件
try:
# 将数据写入到文件中
finally:
file.close()
11.3 迭代文件内容
本节的所有示例中,我都将使用一个名为process的虚构函数来表示对每个字符或行所做的处理,你可以用自己的喜欢的方式实现这个函数。
def process(string):
print('Processing:', string)
11.3.1 每次一个字符(或字节)
with open(filename) as f:
char = f.read(1)
while char:
process(char)
char = f.read(1)
以不同的方式编写循环
with open(filename) as f:
while True:
char = f.read(1)
if not char: break
process(char)
11.3.2 每次一行
with open(filename) as f:
while True:
line = f.readline()
if not line: break
process(line)
11.3.3 读取所有内容
使用read迭代字符
with open(filename) as f:
for char in f.read():
process(char)
使用readlines迭代行
with open(filename) as f:
for line in f.readlines():
process(line)
11.3.4 使用 fileinput 实现延迟行迭代
使用fileinput迭代行
import fileinput
for line in fileinput.input(filename):
process(line)
11.3.5 文件迭代器
迭代文件
with open(filename) as f:
for line in f:
process(line)
sys.stdin也是可迭代的,因此要迭代标准输入中的所有行,可像下面这样做:
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