在Python中,如何计算.txt文件中每行的字符数,并在单独的行上写入另一个.txt文件?

在Python中,如何计算.txt文件中每行的字符数,并在单独的行上写入另一个.txt文件?,python,Python,我是Python新手,一直在努力寻找以下问题的解决方案。我试图计算.txt文件每行中的字符数,然后将这些数字写入另一个文件,该文件将以单独的行显示。例如: inputfile: This code has eight words in it. outputfile: 9 15 6 到目前为止,我提出的代码是将每行计数添加到前一行 wrong output: 9 24 30 这是我的剧本:

我是Python新手,一直在努力寻找以下问题的解决方案。我试图计算.txt文件每行中的字符数,然后将这些数字写入另一个文件,该文件将以单独的行显示。例如:

    inputfile:
    This code
    has eight words 
    in it. 


    outputfile:
    9
    15
    6
到目前为止,我提出的代码是将每行计数添加到前一行

    wrong output:
    9
    24
    30
这是我的剧本:

import sys

infilename = sys.argv[1]
outfilename = sys.argv[2]

infile = open (infilename)
outfile = open (outfilename, "w")

charct = 0

for line in (infile):
    line = line.strip("\n")
    charct = charct + len(line)
    outfile.write(str(charct) + "\n")

infile.close()
outfile.close()

您当前的解决方案使用
charct=charct+len(行)
将当前行长度添加到每行的总长度中。将其替换为
charct=len(line)
就可以了。除此之外,您的代码看起来还不错,不过如果您希望改进代码,您可以使用
with
语句查看打开的文件。

outfile.write(str(len(line))+“\n”)
,无需累加。
charct=charct+len(line)
为什么要添加到计数器中?谢谢。这很有效。我认为我的
charct=charct+len(line)
代码只是单独添加每一行。我没有意识到这就是我累积总数的地方。谢谢你的回复,这有助于澄清混乱。