Python创文本文件

Python创文本文件

问题描述:

编写程序,创建一个文本文件,输入该内容(“中华人民共和国中国人民”)(存放D盘根目录下)打开该文本文件,读出其中内容,统计“中国”关键字出现的次数。

import codecs
import re

wf = codecs.open('D:/test.txt', 'w', 'utf-8')
wf.write('中华人民共和国中国人民')
wf.close()

rf = codecs.open('D:/test.txt', 'r', 'utf-8')
lines = rf.readlines()
rf.close()
count = 0
for line in lines:
    tmp = re.findall('中国', line)
    count += len(tmp)
print(count)

file = open("E:\\test.txt","w") file.write("中华人民共和国中国人民") file.close() file = open("E:\\test.txt","r") A=file.read() B=A.count("中国") print("中国出现次数:{}".format(B))