Skip to content

Python 905 字串資料刪除

Python TQC file

題目說明:

請撰寫一程式,要求使用者輸入檔案名稱data.txt和一字串s,顯示該檔案的內容。接著刪除檔案中的字串s,顯示刪除後的檔案內容並存檔。

範例輸入1
data.txt
Tomato

範例輸出1

=== Before the deletion
Apple Kiwi Banana
Tomato Pear Durian

=== After the deletion
Apple Kiwi Banana
 Pear Durian

範例輸入2

data.txt
Kiwi

範例輸出2

=== Before the deletion
Apple Kiwi Banana
Tomato Pear Durian

=== After the deletion
Apple  Banana
Tomato Pear Durian

data.txt檔案內容

Apple Kiwi Banana 
Tomato Pear Durian

Solution

r = input()
string = input()
f = open(r, 'r+')
d = f.read()
print("=== Before the deletion")
print(d)

print("=== After the deletion")
d = d.replace(string, "")
print(d)
"""
必須回到檔案的頭才能寫入
"""
f.close()
f = open(r, 'w+')
f.write(d)
f.close()

Last update : 13 novembre 2024
Created : 13 novembre 2024

Comments

Comments