繁体   English   中英

如何检查文件的每一行是否以空格开头?

[英]How to check if each line of a file starts with a whitespace?

我正在尝试创建一个遍历代码文件每一行的函数,并检查每一行是否以空白开头。

  # open file for reading
file = open('FileHandle', 'r')

# iterates through each line in file 
for aline in file.readlines():
    # splits each line in file into a separate line
    values = aline.split()
    # removes whitespaces that have been unintentionally added
    values = aline.rstrip() 
    # iterates through each line in file
    for values in aline:
        if values.startswith(' ') == True:
            # the first chacter is a space
            print 'Contains a line that starts with a space.'
        # checks if first character is something other than a space
        if values.startswith(' ') == False:
            # the first character is something other than a space
            # since blank lines contain no characters (not even spaces), this will still
            # be true boolean since '' is not == to ' '. 
            print 'Lines in file do not start with whitespace.'

即使1行以空格开头来打印“包含以空格开头的行”,我也只会得到多个打印的语句,而不是一个简洁的语句。 我假设这与我的打印语句在循环中有关。

问题是因为您正在循环中进行打印。 相反,您可以将结果存储在变量中并在循环后打印:

has_line_starting_with_space = False
for values in aline:
    if values.startswith(' '):
        has_line_starting_with_space = True
        # no need to continue processing
        break
if has_line_starting_with_space:
    print 'Contains a line that starts with a space.'
else:
    print 'Lines in file do not start with whitespace.'

注意:这仅处理空格字符,而不处理其他类型的空格,例如制表符。 要解决这些情况,可以使用re模块。

它非常简单..您所要做的就是仅使用startswith函数检查if条件,您不需要使用“ == true”进行检查。

代码是:

with open("file","r") as readfile:
    for line in readfile:
        if line.startswith( ' ' ):
            print "Contains a line that starts with a space."
        else:
            print "Lines in file do not start with whitespace."

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM