Python基础教程(第3版)中文版 第11章 文件(笔记)

                                    第11章 文件


1.打开文件


使用函数 open 打开文件。
参数是文件名,返回文件对象
例:f = open('somefile.txt')
#如果文件和代码不在一个目录下,需要完整路径
文件模式(mode)
'r' : 读取(默认)
'w' : 写入
'x' : 独占写入,文件已存在时引发异常
'a' : 附加 #文件末尾继续写入
'b' : 二进制
't' : 文本(默认)
'+' : 读写

2.文件的基本方法


1.读取和写入
read 和 write
例:f = open('somefile.txt','w')
f.write('hello, ')
f.write('World!')
f.close()
2.使用管道重定向输出
在bash等shell中,可依次输入多个命令,使用管道(|)链接。
例:$ cat somefile.txt | python somescript.py | sort
3.读取和写入行
readline,提供非负整数(可选)表示读取字符数
readlines,读取所有行,列表形式返回
writelines和readlines相反,接受字符串列表,写入文件。
#没有writeline,因为有write
4.关闭文件
close
要确保文件得以关闭,可使用一条try/finally语句,并在finally子句中调用close。
# 在这里打开文件
try:
 # 将数据写入到文件中
finally:
 file.close()
或者使用with语句
with open("sonefile.txt") as somefile:
    do_someting...

5.使用文件的基本方法(略)

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)
2.每次一行
将上面的read(1)改成readline
with open(filename) as f:
    while True:
        line = f.readline()
        if not line: break
        process(line)
3.读取所有内容
with open(filename) as f:
    for char in f.read():
        process(char)

with open(filename) as f:
    for line in f.readlines():
        process(line)
4.使用fileinput实现延迟行迭代(针对大型文件)
import fileinput
for line in fileinput.input(filename):
    process(line)
5.文件迭代器
文件是可迭代的
with open(filename) as f:
    for line in f:
        process(line)

猜你喜欢

转载自blog.csdn.net/qq_41068877/article/details/82081361