gpt4 book ai didi

python - 如何返回到 Urlopen 对象中的第一行

转载 作者:行者123 更新时间:2023-12-05 07:53:18 26 4
gpt4 key购买 nike

我正在使用 迭代保存在 http 网站上的 .dat 文件

import urllib2
test_file = urllib2.urlopen('http://~/file.dat')

然后,我有一个迭代文件的函数

def f(file):
while True:
iter = file.readline()
if iter == "":
break
print iter

如果我想在不再次打开 test_file 的情况下调用此函数两次:

f(test_file)
f(test_file)

那我应该在f函数里面加什么呢?

更新:由于不允许我更改函数之外的任何内容,我终于想出了一个愚蠢但有效的解决方案:

def f(file):
while True:
iter = file.readline()
if iter == "":
break
print iter
global test_file
test_file = test_file = urllib2.urlopen('http://~/file.dat')

感谢回答我问题的人!

最佳答案

f.seek(0)

返回到文件的开头。参数是文件中的字节位置。

关于python - 如何返回到 Urlopen 对象中的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32750900/

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