Python:从文件读取时出现语法错误

发布于 2024-12-26 11:18:30 字数 532 浏览 0 评论 0原文

我正在从文件中读取数据。数据文件中的大部分数据将不经修改地被读入和写出到输出文件。然而,在某些地方,数据被空行分隔,该空行位于其他 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

月下凄凉 2025-01-02 11:18:30

它不是 Python 中的 elseif,而是 elif

It isn't elseif in python, it's elif.

却一份温柔 2025-01-02 11:18:30

其他人指出它是elif。另外,您在 for 语句末尾缺少一个冒号,Python 可能会抱怨以下行。因此,现在您不必再回来为此提出单独的问题。 :-)

如果您只想迭代文件中的行,更好的方法是:

for testline in testfile:
   # do stuff with the line

您不必以这种方式检查文件结尾,因为当您到达时循环会自动结束文件末尾。

Others have pointed out it's elif. Also, you're missing a colon at the end of your for 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:

for testline in testfile:
   # do stuff with the line

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.

半边脸i 2025-01-02 11:18:30

您正在寻找的不是“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.

ゞ记忆︶ㄣ 2025-01-02 11:18:30

您可以随时尝试将 elseif 更改为 elif

并且您的缩进从第二行开始填充

You could always try changing elseif to elif

And your indentation is stuffed from the 2nd line onwards

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文