如何不计算以'#';在python的文本文件中

如何不计算以'#';在python的文本文件中,python,Python,我有一段代码,它读取文本文件中的行,计算字符数,当达到1000个或更多字符时停止。如何修改它,使其不计算以#符号开头的任何行上的字符 只要在第[0]行中添加!=“#”:到代码: f = open('word_count.txt', 'r') #word_count is just a sample file. char_count = 0 for line in f: if line[0] != "#": char_count = char_count + len(lin

我有一段代码,它读取文本文件中的行,计算字符数,当达到1000个或更多字符时停止。如何修改它,使其不计算以#符号开头的任何行上的字符


只要在第[0]行中添加
!=“#”:
到代码:

f = open('word_count.txt', 'r') #word_count is just a sample file.
char_count = 0
for line in f:
    if line[0] != "#":
        char_count = char_count + len(line)
        if char_count >= 1000:
            break
print("File has %d characters" % (char_count))

语句打开文件。不要读取所有行,只需迭代文件对象即可。将
a=a+b
简称为
a+=b
。检查行是否以
#
string.startswith()
函数开头,并用
而不是
对其求反,以获得所需的条件

你可以这样做:

char_count = 0
with open('word_count.tst', 'r') as f:
    for l in f:
        if not l.startswith('#'):
            char_count += len(l)
            if char_count >= 1000:
                break

如果
line.startswith(“#”)
char_count = 0
with open('word_count.tst', 'r') as f:
    for l in f:
        if not l.startswith('#'):
            char_count += len(l)
            if char_count >= 1000:
                break