#读取文档
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)
python之文件的学习
最新推荐文章于 2023-11-08 21:07:38 发布