既然你要選擇的字符,你可以一次讀取一個字符。
from collections import defaultdict
specific_characters = ['X', 'Y']
counter_dict = defaultdict(lambda: 0)
with open("old.txt", "r") as in_file, open("new.txt","a") as out_file:
while True:
c = in_file.read(1)
if not c:
break
if c in specific_characters:
out_file.write(c)
counter_dict[c] += 1
# printing just X and Y for your specific case.
# the counter will have count of any characters from the specific_characters list.
print "Count of X: ", counter_dict['X']
print "Count of Y: ", counter_dict['Y']
我得問爲什麼?這看起來不太直觀。你是否想要計算某些字符被發現的實例的數量?或者是什麼?我認爲你在這裏實際嘗試做的更多細節是有序的。 – KronoS
順便說一句,你應該使用:'with open('old.txt','r')作爲in_file,open('new.txt','w')作爲out_file:'而不是明確地打開和關閉文件。 – KronoS