簡體   English   中英

為什么我不能同時在Python中的文件中寫入2個變量

[英]Why can't I write 2 variables at the same time to a file in Python

我有以下代碼:

def yaml_processor(period):
    filepath_reg = "../public/log/testing.log.yaml"
    data = yaml_loader(filepath)
    data = data.get(period)
    for team, key in data.iteritems():
        file = open("test.log.yaml", 'w')
        file.write('%team %period\n')
        file.close()
        print(team, period)

它不想將它們寫入file.write('{team}, {period}\\n') ,但是可以完美地打印值...

我在這里做錯了什么?

您需要學習字符串格式化

嘗試將file.write('%team %period\\n')替換為

file.write('{} {}\n'.format(team, period))

如果您使用的是最新版本的Python(3.6或更高版本),則可以利用f-strings

with open("test.log.yaml", 'w') as file:
    file.write(f'{team} {period}\n')

您將在循環的每次迭代中打開文件,該循環將刪除先前的值。 只需將open和close語句移出循環即可。

def yaml_processor(period):
filepath_reg = "../public/log/testing.log.yaml"
data = yaml_loader(filepath)
data = data.get(period)
file = open("test.log.yaml", 'w')
for team, key in data.iteritems():
    file.write('%team %period\n')
    print(team, period)
file.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM