简体   繁体   中英

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 ...

What am I doing wrong here?

You need to learn string formatting .

Try replacing file.write('%team %period\\n') with

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 :

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM