10-1 Python学习笔记
filename = 'learning_python.txt'
# 第一次打印读取整个文件
with open(filename) as file_object:
contents = file_object.read()
print(contents)
# 第二次打印时遍历文件对象
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
# 第三次打印时将各行存储在一个列表中,再在with代码块外打印它们
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
10-2 C语言学习笔记
filename = 'learning_python.txt'
with open(filename) as file_object:
message = file_object.read()
print(message.replace('Python', 'C'))
注意单独调用方法replace不会改变message本身的值,所以如果采用下述写法message的输出并不会变。
---snip---
message.replce('Python', 'C')
print(message)
使用方法replace重新赋值,则输出改变。
message = message.replace('Python', 'C')
print(message)