python之文件的学习

#读取文档
f = open("a.txt",'r')
print(f.read(4))
print(f.read())
f.close()

#写文档
f = open("a.txt",'w')
f.write('hello,')
f.write('world!')
f.write('hello,')
f.write('world!')
f.write('hello,')
f.write('world!')
f.write('hello,')
f.write('world!')
f.close()

#追加模式
f = open("a.txt",'a')
f.write('hello,')
f.write('world!\n')
f.write('hello,')
f.write('world!\n')
f.write('hello,')
f.write('world!\n')
f.write('hello,')
f.write('world!\n')
f.close()

#readline()(读一行)
f = open("a.txt",'r')
for i in range(10):
	print(f.readline())
f.close()

#readlines和writelines(读全部和写全部)
f = open("a.txt",'r')
lines = f.readlines()
print(lines)
f.close()
f = open("b.txt",'w')
f.writelines(lines)
f.close()

文件内容进行迭代
#按字节处理
def process(string):
	print(string)

f = open("a.txt",'r')
char = f.read(1)
while char:
	process(char)
	char = f.read(1)
f.close()

#按行处理
f = open("a.txt",'r')
while True:
	line = f.readline()
	if not line: break
	process(line)
f.close()

#用read迭代每个字符
f = open("a.txt",'r')
for char in f.read():
	process(char)
f.close()

用readlines迭代行
f = open("a.txt",'r')
for line in f.readlines():
	process(line)
f.close()

文件迭代器
f = open("a.txt",'r')
for line in f:
	process(line)
f.close()

for line in open("a.txt",'r'):
	process(line)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值