Python程式設計 從入門到實踐 練習10-1、練習10-2
阿新 • • 發佈:2021-02-05
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)