python_文件操作练习题

1.在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python 知识,其中每一行都以“In Python you can”打头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中。

代码:

for i in range(3):
if i ==0:
with open(‘learning_python.txt’,‘r’,encoding=‘utf-8’) as files:
content=files.read()
print(‘one’)
print(content)
if i ==1:
with open(‘learning_python.txt’,‘r’,encoding=‘utf-8’) as files:
print(‘two’)
print(content)
if i ==2:
with open(‘learning_python.txt’,‘r’,encoding=‘utf-8’) as files:
content=files.readlines()
print(‘three’)
print(content)

输出:
one
In Python you can 111111111
In Python you can 22222222
In Python you can 33333333333
two
In Python you can 111111111
In Python you can 22222222
In Python you can 33333333333
three
[‘In Python you can 111111111\n’, ‘In Python you can 22222222\n’, ‘In Python you can 33333333333\n’]

‘’’

访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写 入到文件guest.txt 中。

程序判断当不等于n的时候,就执行。

while True:
name = input(‘请输入您的姓名:’)
if name == ‘n’:
break;
with open(‘guest.txt’,‘a+’,encoding=‘utf-8’) as files: #累加写的方式写入文件。
files.write(name)
files.write(’\n’)
files.seek(0)
content = files.read()
print(content)

请输入您的姓名:123456
joe
susan
anna
123456
请输入您的姓名:

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值