繁体   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