相关疑难解决方法(0)

为什么我不能在打开的文件上调用read()两次?

对于我正在进行的练习,我正在尝试使用该read()方法两次读取给定文件的内容.奇怪的是,当我第二次调用它时,它似乎没有将文件内容作为字符串返回?

这是代码

f = f.open()

# get the year
match = re.search(r'Popularity in (\d+)', f.read())

if match:
  print match.group(1)

# get all the names
matches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', f.read())

if matches:
  # matches is always None
Run Code Online (Sandbox Code Playgroud)

当然我知道这不是最有效或最好的方式,这不是重点.关键是,为什么我不能read()两次打电话?我是否必须重置文件句柄?或者关闭/重新打开文件以执行此操作?

python io

86
推荐指数
4
解决办法
6万
查看次数

使用Python迭代文件

我有一个问题要理解迭代文件,在这里我继续我在解释器上输入的内容和结果:

>>> f = open('baby1990.html', 'rU')
>>> for line in f.readlines():
...  print(line)
... 
# ... all the lines from the file appear here ...
Run Code Online (Sandbox Code Playgroud)

当我再次尝试迭代同一个打开的文件时,我什么也没得到!

>>> for line in f.readlines():
...  print(line)
... 
>>>
Run Code Online (Sandbox Code Playgroud)

根本没有输出,为了解决这个问题,我要关闭()文件,然后再打开它进行阅读!! 这是正常的行为吗?

python iteration file

51
推荐指数
3
解决办法
11万
查看次数

标签 统计

python ×2

file ×1

io ×1

iteration ×1