第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')