《python基础教程》 --读书笔记(10)

文件和流

打开文件

open函数用来打开文件:
open(name[, mode[, buffering]])
文件模式
open函数中模式参数常用值

描述
“r”读模式
“w”写模式
“a”追加模式
“b”二进制模式(可添加到其他模式中)
“+”读/写模式(可添加到其他模式中)

缓冲
open函数的第3个参数控制着文件的缓冲,如果参数是0(False),I/O就是无缓冲的(所有读写操作都直接针对硬盘);如果是1(True),I/O就是有缓存的(一位着python使用内存来代替硬盘,让程序更快,只有使用flush或者close时才会更新硬盘上的数据)大于1的数字代表缓冲区的大小(字节),-1或者任何负数代表使用默认的缓冲区大小

基本文件方法


# read()
f = open(r"somefile.txt")
print(f.read())
print("_____")
f.close()

# read(n)
f = open(r"somefile.txt")
print(f.read(7))
print(f.read(4))
print("_____")
f.close()

# readline()
f = open(r"somefile.txt")
print(f.readline())
print("_____")
f.close()

# readlines()
f = open(r"somefile.txt")
print(f.readlines())
print("_____")
f.close()

# write(string)
w = open(r"somefile_r.txt", "w")
w.write("this\nis no\nhaiku")
w.close()

# writelines(string)
wr = open(r"somefile_r.txt")
lines = wr.readlines()
wr.close()
lines[1] = "isn't a\n"
ww = open(r"somefile_r.txt", "w")
ww.writelines(lines)
ww.close()

文件内容进行迭代


def process(string):
    print("Processsing: ", string)

# 用read方法对每个字符进行循环

f = open(r"somefile.txt")
while True:
    char = f.read(1)
    if not char: break
    process(char)
f.close()

# 使用readline按行操作
f = open(r"somefile.txt")
while True:
    line = f.readline()
    if not line: break
    process(line)
f.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值