简体   繁体   中英

Iteratively writing to a file in Python, creating a new string in each iteration

I'm missing the obvious, I think, but I'd be grateful to someone who points it out. It's been an hour of playing with syntax and I'm frustrated.

The following is an MWE. It takes less than 1 second to run:

from itertools import product

PARAM_GRID = list(product(
range(64, 68),
range(64, 68),
range(132, 136),
range(132, 136),
))

SCOREFILE = './fake_scores.csv'

def search_distributed():

    for param_ix in range(len(PARAM_GRID)):

        params = PARAM_GRID[param_ix]
        score = 0.9

        with open(SCOREFILE, 'a') as f:
            #NOT MINE, and doesn't do what I want
            #f.write('{",".join(map(str, params + (score,)))}\n')

            #MINE, and still doesn't do what I want.
            paramstr = str(params) 
            scorestr = str(score) 
            f.write("\n".join({paramstr + ' ' + scorestr}))

def main():
    search_distributed()

if __name__ == '__main__':
    main()

Instead of what this creates, which is a file containing:

(64, 64, 132, 132) 0.9(64, 64, 132, 133) 0.9(64, 64, 132, 134) 0.9...

I want a file containing:

(64, 64, 132, 132) 0.9
(64, 64, 132, 133) 0.9
(64, 64, 132, 134) 0.9

Obviously I need to modify the join command somehow. I've shown my attempt above. Can anyone fix this?

Here is a small tweak of your code to solve your issue :

from itertools import product

PARAM_GRID = list(product(
range(64, 68),
range(64, 68),
range(132, 136),
range(132, 136),
))

SCOREFILE = './fake_scores.csv'

def search_distributed():

    for param_ix in range(len(PARAM_GRID)):

        params = PARAM_GRID[param_ix]
        score = 0.9

        with open(SCOREFILE, 'a') as f:
            #NOT MINE, and doesn't do what I want
            #f.write('{",".join(map(str, params + (score,)))}\n')

            #MINE, and still doesn't do what I want.
            paramstr = str(params) 
            scorestr = str(score) 
            f.write(paramstr + ' ' + scorestr + '\n')

def main():
    search_distributed()

if __name__ == '__main__':
    main()

As your are giving only one element ( {paramstr + ' ' + scorestr} is only one string, not an list of elements) to the join method, it doesn't add any "\\n". You just need to manually add it to the end of each one of your lines.

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