文件的读写
<1>写数据(write)
使用write()可以完成向文件写入数据
Demo
1 2 3 | f = open ( 'test.txt' , 'w' ) f.write( 'hello world, i am here!' ) f.close() |
<2>读数据(read)
使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据
demo:
1 2 3 4 5 6 7 8 9 10 | f = open ( 'test.txt' , 'w' ) f.write( 'hello world, i am here!' ) f.close() f = open ( 'test.txt' , 'r' ) content = f.read( 5 ) print (content) print ( "-" * 30 ) content = f.read() print (content) f.close() |
运行结果:
hello
------------------------------
world, i am here!
<3>读数据(readlines)
就像read没有参数时一样,readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素
1 2 3 4 5 6 7 8 9 10 11 | f = open ( 'test.txt' , 'w' ) f.write( 'hello world, i am here!' ) f.close() f = open ( 'test.txt' , 'r' ) content = f.readlines() print ( type (content)) i = 1 for temp in content: print ( "%d:%s" % (i, temp)) i + = 1 f.close() |
运行结果:
<class 'list'>
1:hello world, i am here!
<4>读数据(readline)
1 2 3 4 5 6 7 8 9 | f = open ( 'test.txt' , 'w' ) f.write( 'hello world, i am here!' ) f.close() f = open ( 'test.txt' , 'r' ) content = f.readline() print ( "1:%s" % content) content = f.readline() print ( "2:%s" % content) f.close() |
运行结果:
1:hello world, i am here!
2:
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步