1.打开文件
open函数的定义如下
open(file,mode='r',buffering=-1,encoding=None,errors=None,newline=None,closed=True,opener=None)
用open函数,open函数有很多参数,只有file参数是必须传递的,其他参数都有默认值,最简单的打开文件的例子
file_name="fibs.py"
f=open(file_name)
1.1文件模式
默认模式为r,其他模式:rb,r+,rb+,w,wb,w+,wb+,a,ab,a+,ab+
2.文件基本操作
2.1读文件
f=open("readme.txt")
txt=f.read()
print(txt)
Hello world!
f=open("readme.txt")
txt=f.read(20)
print(txt)
Hello world!
2.2写文件
with open("LICENSE.txt","w") as f:
txt="写入文件"
print(f.write(txt))
4
from datetime import datetime
with open("appendme.txt","a") as f
now=str(datatime.now())+"\n"
print(f.write(now))
27
2.3按行读文件
f=open("appendme.txt","r")
print(f.readline())
print(f.readline())
2024-03-17 13:31:21.729525
2024-03-17 14:31:08.670898
f=open("appendme.txt","r")
for line in f.readlines():
print(line)
直接迭代文件对象本身
with open("appendme.txt","r") as f:
for line in f:
print(line)
2.4按行写文件
f=open("writelines.txt","w")
lines=[]
for i in range(10):
lines.append(str(i))
f.writelines(lines)
2.5关闭文件
with open("writelines.txt","w") as f:
f.close()
引入with语句帮我们自动调用close方法。
with open("readme.txt","r") as f:
content=f.read()
print(content)
3.StringIO和BytesIO
from io import StringIO
f=StringIO()
f.write('hello')
f.write('')
f.write('world!')
print(f.getvalue())
helloworld!
from io import StringIO
f=StringIO('Hello!\nworld!\nwelcome!')
while True:
s=f.readline()
if s=='':
break
print(s.strip())
Hello!
world!
welcome!
写入一些bytes
from io import BytesIO
f = BytesIO()
f.write("您好".encode("utf-8"))
print(f.getvalue())
print(f.getvalue().decode("utf-8"))
b'\xe6\x82\xa8\xe5\xa5\xbd'
您好
这里写入的不是str,而是经过UTF-8编码的bytes.
from io import BytesIO
f=BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
print(f.read().decode("utf-8"))
中文