简体   繁体   中英

Printing inside a for-loop

(Sorry for any mistakes, english is my second language and I'm still learning)

I'm trying to automate some things in my guitar warmups and scales practice and got stuck at this point. First I wrote this code to randomly select three finger patterns and that the chosen items in the set would be selected again only after all the other items be chosen, but got nothing in fingerPatternLoop.txt and nothing at terminal.

import random

fingerPatterns = set(['1, 2, 3, 4', '1, 2, 4, 3', '1, 3, 4, 2', '1, 3, 2, 4', 
'1, 4, 3, 2', '1, 4, 2, 3', '2, 1, 3, 4', '2, 1, 4, 3', '2, 3, 1, 4', 
'2, 3, 4, 1', '2, 4, 3, 1', '2, 4, 1, 3', '3, 1, 2, 4', '3, 1, 4, 2', 
'3, 2, 4, 1', '3, 2, 1, 4', '3, 4, 2, 1', '3, 4, 1, 2', '4, 1, 2, 3', 
'4, 1, 3, 2', '4, 2, 1, 3', '4, 2, 3, 1', '4, 3, 1, 2', '4, 3, 2, 1', 
    ])

fingerPatternLoop = open("fingerPatternLoop.txt", "a+")
rand_warmup = random.sample(fingerPatterns, 3)

for rand_warmup in fingerPatternLoop:
    if rand_warmup not in fingerPatternLoop:
        print(rand_warmup)
        print(f"{rand_warmup}", file=fingerPatternLoop)

Removing the for loop made the code work.

print(rand_warmup)
print(f"{rand_warmup}", file=fingerPatternLoop)

But I still can't figure out how to make those prints work inside a for loop that verify if any of the items of the random.sample already occurred and clear the fingerPatternLoop.txt in the case of all 24 items already been chosen.

The filemode a+ is never useful. You open the file for reading and writing, setting the filepointer at the end. So reading never enters the for loop.

You have to read and write the file in two steps.

rand_warmup = random.sample(fingerPatterns, 3)
with open("fingerPatternLoop.txt") as lines:
    found = rand_warmup in map(str.strip, lines)

if not found:
    with open("fingerPatternLoop.txt", "a") as output:
        print(rand_warmup, file=output)

The fingerpatternLoop variable is a file object, you have to read it and store its content in a variable, like with:

with open('fingerPatterLoop.txt', 'r') as f:
    data = f.readlines()

if str(rand_warmup) not in data:
    # write to file

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