如以下代码:写两次yaml.load(f),第二次打印出来内容是none,什么原因?
import yaml, os
# Create your tests here.
base_dir = os.path.dirname(os.path.dirname(__file__))
file_dir = base_dir + '/case_data/test.yml'
with open(file_dir, 'r', encoding='utf-8') as f:
print(yaml.load(f))
a = yaml.load(f)
print(a)
执行结果:

原来是因为第一次加载后,文件游标指向文件最后,第二次加载就没有内容了,第二次加载前把游标指向文件开头即可,f.seek(0)
import yaml, os
# Create your tests here.
base_dir = os.path.dirname(os.path.dirname(__file__))
file_dir = base_dir + '/case_data/test.yml'
with open(file_dir, 'r', encoding='utf-8') as f:
print(yaml.load(f))
f.seek(0)
a = yaml.load(f)
print(a)
执行结果:

探讨了在Python中使用yaml模块加载同一文件两次时,第二次读取返回None的原因,并给出了通过将文件指针重置到文件开头来解决此问题的方法。

被折叠的 条评论
为什么被折叠?



