Python程序设计( 五 文件操作、综合应用)——5.2 文件的读写

5.2.1 写数据(write)

使用write()可以完成向文件写入数据
示例如下:

f = open('test.txt', 'w')
f.write('hello world, i am here!')
f.close()

运行现象:
在这里插入图片描述
注意:如果文件不存在那么创建,如果存在那么就先清空,然后写入数据

5.2.2 读数据(read)

使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据
示例如下:

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!

注意:
● 如果open是打开一个文件,那么可以不用写打开的模式,即只写 open(‘test.txt’)
● 如果使用读了多次,那么后面读取的数据是从上次读完后的位置开始的

5.2.3 读数据(readlines)

就像read没有参数时一样,readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素

f = open('test.txt', 'r')
content = f.readlines()
print(content)
print(type(content))
i = 1
for temp in content:
    print("%d:%s" % (i, temp),end='')
    i += 1
f.close()

程序运行结果如下:

['hello world, i am here!\n', 'hello world, i am here!!\n', 'hello world, i am here!!!']
<class 'list'>
1:hello world, i am here!
2:hello world, i am here!!
3:hello world, i am here!!!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值