[英]Python Files word count and character count
Picture of Question: 问题图片:
I have this code but it just outputs a blank file. 我有这段代码,但它只输出一个空白文件。 What am I doing wrong?
我究竟做错了什么?
def lineStats(infile, outfile):
inF = open(infile, 'rt')
outF = open(outfile, 'wt')
content = inF.readlines()
for line in inF:
wordcount = len(line.split())
charcount = len(line)
outF.write(str(wordcount) + ' ' + str(charcount))
inF.close()
outF.close()
lineStats('promisedLand.txt', 'promisedLandStats.txt')
You have two problems, you're consuming your file when you do the following (delete this line): 您有两个问题,执行以下操作会消耗您的文件(删除此行):
content = inF.readlines()
And you forgot to write newlines each time you call write
: 而且您每次调用
write
时都忘记写换行符:
outF.write(str(wordcount) + ' ' + str(charcount) + '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.