简体   繁体   中英

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

I'm trying to create a function that iterates through each line of a code file and checks to see if each line starts white 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.'

I keep just getting multiple printed statements instead of a single concise statement, even if 1 line starts with a whitespace to print 'Contains a line that starts with a space.'. I'm assuming this has to do with that that my print statements are in the loop.

The problem is because you are printing from within the loop. Instead, you can store the results in a variable and print after the loop:

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.'

Note: this only handles space character and not other types of whitespace such as tabs. To cover those cases, you can use the re module.

Its pretty simple..All you have to do is Just check the if condition only with startswith function, You don't need that should check with "== true"..

Code is:

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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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