既然你要选择的字符,你可以一次读取一个字符。
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