简体   繁体   English

为什么我不能同时在Python中的文件中写入2个变量

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

I have this code: 我有以下代码:

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)

It doesn't want to write them file.write('{team}, {period}\\n') , but prints the values perfectly ... 它不想将它们写入file.write('{team}, {period}\\n') ,但是可以完美地打印值...

What am I doing wrong here? 我在这里做错了什么?

You need to learn string formatting . 您需要学习字符串格式化

Try replacing file.write('%team %period\\n') with 尝试将file.write('%team %period\\n')替换为

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

If you're using a recent version of Python (3.6 or later), you can take advantage of f-strings : 如果您使用的是最新版本的Python(3.6或更高版本),则可以利用f-strings

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

You are opening the file in each iteration of the loop which removes the previous values. 您将在循环的每次迭代中打开文件,该循环将删除先前的值。 Just move the open and close statement out of the loop. 只需将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