Python:从文件读取时出现语法错误
我正在从文件中读取数据。数据文件中的大部分数据将不经修改地被读入和写出到输出文件。然而,在某些地方,数据被空行分隔,该空行位于其他 5 个无用行之前。这是我的代码:
#Now loop over the entire file
while True:
testline = infile.readline()
if len(testline) ==0:
break # EOF
elseif testline == '\n':
for i in range(0,5)
testline = infile.readline()
else:
outfile.write(testline)
我收到以下错误,这让我感到困惑:
File "convert.py", line 31
elseif testline == '\n':
^
SyntaxError: invalid syntax
有什么想法吗?我无法弄清楚我的 elseif 语句有什么问题。
I'm reading data from a file. Most of the data in the data file will be read in and written out to an output file without modification. However, in places the data is separated by a blank line, which precedes 5 other useless lines. Here is my code:
#Now loop over the entire file
while True:
testline = infile.readline()
if len(testline) ==0:
break # EOF
elseif testline == '\n':
for i in range(0,5)
testline = infile.readline()
else:
outfile.write(testline)
I get the following error that has me stumped:
File "convert.py", line 31
elseif testline == '\n':
^
SyntaxError: invalid syntax
Any thoughts? I can't figure out what is wrong with my elseif statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它不是 Python 中的
elseif
,而是elif
。It isn't
elseif
in python, it'selif
.其他人指出它是
elif
。另外,您在for
语句末尾缺少一个冒号,Python 可能会抱怨以下行。因此,现在您不必再回来为此提出单独的问题。 :-)如果您只想迭代文件中的行,更好的方法是:
您不必以这种方式检查文件结尾,因为当您到达时循环会自动结束文件末尾。
Others have pointed out it's
elif
. Also, you're missing a colon at the end of yourfor
statement, and Python will probably complain about the following line. So now you don't have to come back and ask a separate question for that. :-)If you just want to iterate over the lines in a file, though, a better way to do this is:
You don't have to check for the end-of-file that way because the loop automatically ends when you reach the end of the file.
您正在寻找的不是“elseif”,而是“elif”。
此外,在 for 循环的末尾还有另一个拼写错误
for i in range(0,5)
它需要在末尾有一个 : 。It isn't 'elseif' it is 'elif' that you are looking for.
Furthermore there is another typo at the end of your for loop
for i in range(0,5)
it needs a : at the end there.您可以随时尝试将
elseif
更改为elif
并且您的缩进从第二行开始填充
You could always try changing
elseif
toelif
And your indentation is stuffed from the 2nd line onwards