第10章作业
习题10-1
learning_python.txt
In Python you can work
In Python you can sleep
In Python you can be lazy
a.py
filename = 'learning_python.txt'
with open(filename) as f:
contents = f.read()
print(contents)
with open(filename) as f:
for line in f:
print(line)
with open(filename) as f:
lines = f.readlines()
for line in lines:
print(line)
Output
In Python you can work
In Python you can sleep
In Python you can be lazy
In Python you can work
In Python you can sleep
In Python you can be lazy
In Python you can work
In Python you can sleep
In Python you can be lazy
多余的换行是因为读取文件时有一个换行,print语句也加了个换行
习题10-3
guest = input('Your name: ')
with open('guest.txt', 'w') as f:
f.write(guest)
习题10-5
with open('reason.txt', 'w') as f:
pass
while True:
reason = input('Your reason: ')
if reason == 'exit':
break
with open('reason.txt', 'a') as f:
f.write(reason)
f.write('\n')
本文通过几个具体的Python编程实例展示了如何进行文件的读写操作,包括读取文本文件内容并打印,记录用户姓名到文件中,以及连续收集并保存用户输入的原因。
1368

被折叠的 条评论
为什么被折叠?



