簡體   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