《python基础教程(第二版)》学习笔记 文件和素材(第11章)

《python基础教程(第二版)》学习笔记 文件和素材(第11章)

打开文件:
open(filename[,mode[,buffering]])

mode是读写文件的模式
f=open(r'c:somefile.txt') #默认是读模式
+ 表示是可以读写;r 读模式;w 写模式;a 追加模式;b 二进制模式;
换行符在Windows为 ,在Unix中为 , Python会自动转换;

buffering缓冲;0表示无缓冲;1表示有缓冲(使用flush或close才会写到硬盘中);

sys.stdin 标准输入;sys.stdout 标准输出; sys.stderr 错误信息;

f=open('aaa.txt','w')
f.write('Hello,')
f.write('world!')
f.close()

f=open('aaa.txt','r')
f.read(4) # 读取4个字符
f.read() # 读取剩余的内容

管道输入/输出
text=sys.stdin.read()

f.readline() 读取一行
f.readline(5) 读5个字符
f.readlines() 读取全部行并作为列表返回
f.writelines() 输入参数是列表,把内容写入到文件中;不会添加新行;

关闭文件 f.close()

with open('aaa.txt') as somefile:
   do_something(somefile)

按字节处理
f=open(filename)
char=f.read(1)
wile char:
  process(char)
  char=f.read()
f.close()

f=open(filename)
while True:
  char=f.read(1)
  if not char: break
  process(char)
f.close()

按行处理
f=open(filename)
while True:
  line=f.readline()
  if not line: break
  process(line)
f.close()

用read迭代每个字符
f=open(filename)
for char in f.read():
  process(char)
f.close()

用readlines迭代行
f=open(filename)
for line in f.realines():
  process(line)
f.close()

对大文件实现懒惰行迭代
import fileinput
for line in fileinput.input(finename):
   process(line)
   
迭代文件
f=open(filename)
for line in f:
   process(line)
f.close()

原文地址:https://www.cnblogs.com/emanlee/p/4033526.html