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

时间:2017-10-29 03:48:38

标签: python

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

  # 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行以空格开头打印'包含以空格开头的行'。我假设这与我的print语句在循环中有关。

2 个答案:

答案 0 :(得分: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模块。

答案 1 :(得分:0)

它非常简单..你要做的就是只检查if条件只能使用startswith功能,你不需要检查" == 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."