【Python之坑】寫兩次yaml.load(f),第二次打印出來內容是none
阿新 • • 發佈:2018-11-20
如以下程式碼:寫兩次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)
執行結果: