[英]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.'. 即使1行以空格开头来打印“包含以空格开头的行”,我也只会得到多个打印的语句,而不是一个简洁的语句。 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. 要解决这些情况,可以使用
re
模块。
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".. 它非常简单..您所要做的就是仅使用startswith函数检查if条件,您不需要使用“ == 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."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.