【Python之坑】写两次yaml.load(f),第二次打印出来内容是none

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bubblelone/article/details/84031376

如以下代码:写两次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)

  执行结果:

 

猜你喜欢

转载自blog.csdn.net/bubblelone/article/details/84031376