gpt4 book ai didi

Python连续读取文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:56:06 25 4
gpt4 key购买 nike

我有一个从文件中读取的 Python 脚本。第一个命令计算行数。第二个打印第二行,尽管第二个不工作。

lv_file = open("filename.txt", "rw+")

# count the number of lines =================================
lv_cnt = 0
for row in lv_file.xreadlines():
lv_cnt = lv_cnt + 1

# print the second line =====================================
la_lines = la_file.readlines()
print la_lines[2]

lv_file.close()

当我这样写它时它可以工作,但我不明白为什么我必须关闭文件并重新打开它才能让它工作。我是否滥用了某种功能?

lv_file = open("filename.txt", "rw+")

# count the number of lines =================================
lv_cnt = 0
for row in lv_file.xreadlines():
lv_cnt = lv_cnt + 1

lv_file.close()

lv_file = open("filename.txt", "rw+")

# print the second line =====================================
la_lines = la_file.readlines()
print la_lines[2]

lv_file.close()

最佳答案

文件对象是一个迭代器。一旦您遍历了所有行,迭代器就用完了,进一步的读取将无济于事。

要避免关闭并重新打开文件,您可以使用 seek 倒回到开头:

lv_file.seek(0)

关于Python连续读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30165948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com