readline() 正在跳过源文件中的行

发布于 2024-11-18 21:56:32 字数 529 浏览 3 评论 0原文

我有一个用多行创建的 .txt 文件。

当我使用计数累加器运行 for 循环时,它会跳过行。

它跳过顶行,从第二行开始,打印第四行、第六行等。

我错过了什么?

def main():
    # Open file line_numbers.txt
    data_file = open('line_numbers.txt', 'r')

    # initialize accumulatior
    count = 1
      

    # Read all lines in data_file
    for line in data_file:
        # Get the data from the file
        line = data_file.readline()

        # Display data retrieved
        print(count, ": ", line)

        # add to count sequence
        count += 1

I have a .txt file that I created with multiple lines.

When I run a for loop, with a count accumulator, it skips lines.

It skips the top line, and starts with the second, prints the fourth, the sixth, etc.

What is it I'm missing?

def main():
    # Open file line_numbers.txt
    data_file = open('line_numbers.txt', 'r')

    # initialize accumulatior
    count = 1
      

    # Read all lines in data_file
    for line in data_file:
        # Get the data from the file
        line = data_file.readline()

        # Display data retrieved
        print(count, ": ", line)

        # add to count sequence
        count += 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

夏夜暖风 2024-11-25 21:56:32

尝试完全删除“line=data_file.readline()”?我怀疑“for line in data_file:”也是一个 readline 操作。

Try removing the "line=data_file.readline()" altogether? I suspect the "for line in data_file:" is also a readline operation.

回忆那么伤 2024-11-25 21:56:32

您的 for 循环正在迭代 data_file 并且您的 readline() 正在与之竞争。删除代码中的 line = data_file.readline() 行以获得此结果:

# Read all lines in data_file
count = 1
for line in data_file:
    # Display data retrieved
    print(count, ": ", line)

    # add to count sequence
    count += 1

You for loop is iterating over the data_file and your readline() is competing with it. Erase the line = data_file.readline() line of your code for this result:

# Read all lines in data_file
count = 1
for line in data_file:
    # Display data retrieved
    print(count, ": ", line)

    # add to count sequence
    count += 1
离鸿 2024-11-25 21:56:32

for line in data_file 已经为您获取了每行的文本 - 随后对 readline 的调用将获取下面行。换句话说,删除对 readline 的调用将执行您想要的操作。同时,您不需要自己跟踪累加器变量 - python 有一个使用 enumerate 执行此操作的内置方法 - 换句话说:

data_file = open('line_numbers.txt', 'r')
for count, line in enumerate(data_file):
    ...

for line in data_file already gets the text of each line for you - the subsequent call to readline then gets the following line. In other words, removing the call to readline will do what you want. At the same time, you don't need to keep track of an accumulator variable yourself - python has a built-in way of doing this using enumerate - in other words:

data_file = open('line_numbers.txt', 'r')
for count, line in enumerate(data_file):
    ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文