文件与IO

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"))

中文

  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值