文件和流
打开文件
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()