2019实战第二期-文件读书打卡

-----学习《Python基础教程第3版》读书笔记-----

打开文件

​ 要打开文件,使用open函数,不需要导入模块io,它会自动导入。

f = open('test.txt')  #也可以指定全路径

​ 文件常见打开模式

f = open('test.txt', 'r')# 读取模式,也是默认值
f = open('test.txt', 'w')# 写入模式。能够写入文件,并在文件,不存在时创建它
f = open('test.txt', 'x')# 独占写入模式,如果文件存在则会报错
f = open('test.txt', 'a')# 追加模式
f = open('test.txt', 'b')# 二进制模式
f = open('test.txt', 't')# 文本模式
f = open('test.txt', '+')# 可与其他任何模式结合起来使用,表示既可读取也可写入
# 例如
open('test.txt', 'r+')   open('test.txt', 'w+')

​ Python使用通用换行模式

文件的基本方法

读取和写入
# 写入
f = open('somefile.txt', 'w')
f.write("Hello,")
f.write("World")
f.close()

# 读取
f = open('somefile.txt', 'r')
f.read(4)
f.read()
使用管道重定向输出
# somescript.py
import sys
text = sys.stdin.read()
words = text.split()
wordcount = len(words)
print('Wordcount:', wordcount)

# 编写文本somefile.txt内容:
Your mother was a hamster and your
father smelled of elderberries.
>> cat somefile.txt | python somescript.py 的结果如下:
Wordcount: 11
读取和写入行
f = open('somefile.txt', 'r')
f.readline()# 读取一行,可以不断循环读取,知道读完
f.readlines()# 读取所有行,如果文件大,容易出现内存溢出
写可以用write
关闭文件
# 养成习惯,操作完成要对文件进行关闭。
# 写入过的文件,一定要将其关闭,因为Python可能缓冲你写入的数据
# 在这里打开文件
try:
    # 将数据写入到文件中
finally:
    file.close()
当然,还有一种好方法,专门会关闭文件流
with open("somefile.txt") as somefile:
    do_something(somefile)

使用文件的基本方法

f = open("somefile.txt", 'w+')
f.read(4) # 代表读取4个字符
f.read() # 读取完所有剩下没读取的内容
f.readline()# 读取一行,可以不断循环读取,知道读完
f.readlines()# 读取所有行,返回列表,如果文件大,容易出现内存溢出
f.write("hello")# 写内容

迭代文件内容

def process(string):
    print('Processing:', string)

# 每次一个字符读取
with open(filename) as f:
    while True:
        char = f.read(1)
        if not char: break
        process(char)
        
# 每次一行
with open(filename) as f:
    while True:
        line = f.readline()
        if not line: break
        process(line)
        
# 读取所有内容
# 使用 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)
    
# 使用fileinput实现延迟迭代
import fileinput
for line in fileinput.input(filename):
    process(line)
    
# 文本迭代器
with open(filename) as f:
    for line in f:
        process(line)

常见的文件的模块的使用:os模块, shutil模块,walk模块

你可能感兴趣的:(2019实战第二期-文件读书打卡)