trunting trunting - 1 year ago 95
Python Question

python only writes last output to file

I am trying to write a program that picks a random musical scale until all have been chosen, and the problem I have is that my code is only writing one line to my text file.

I know this is a similar question to Python: Only writes last line of output but I have already tried the solution to open and then close the file outside of the loop (at least to the best of my ability, please correct me if I'm wrong).

My code is this:

#imports the required library
import random

#picks 1 hands separate major scale
def MajorScalesHandsSeparate():

#initialises the chars variable
chars = 0

#creates the checker file if it has not previously been created
while True:
with open('MajorScalesHandsSeparate.txt', 'a') as f:

#counts the number of chars in the file
with open('MajorScalesHandsSeparate.txt', 'r') as f:
for line in f:
chars += len(line)

#converts file to list
with open('MajorScalesHandsSeparate.csv', 'r') as f:
MajorScalesHandsSeparate = [line.strip() for line in f]

#opens file to check for the number of lines
with open('MajorScalesHandsSeparate.csv', 'r') as f:
Items = sum(1 for _ in f)

#asks the user how many scales they would like
NumScales = input("How many hands separate major scales would you like? ")

#resets the loop counter and picker to 0
WhileControl = 0
ScalePicker = 0

checker = open('MajorScalesHandsSeparate.txt', 'w+')
#choses a number
while WhileControl != NumScales:
ScalePicker = random.randint(0, Items-1)

#checks if scale has already been chosen
if MajorScalesHandsSeparate[ScalePicker] not in open('MajorScalesHandsSeparate.txt').read():

#writes scale to file
checker.write(Scale + '\n')

#prints chosen scale
print MajorScalesHandsSeparate[ScalePicker]

#increments the loop counter by one
WhileControl = WhileControl + 1

#removes item from list
Items = Items - 1

#checks if all scales have been used
if len(MajorScalesHandsSeparate) == 0:
with open('MajorScalesHandsSeparate.csv', 'r') as f:
#converts file to list once again
MajorScalesHandsSeparate = [line.strip() for line in f]

#closes the file

#calls the function

My output looks like this:

How many hands separate major scales would you like? 3
Db major RH only
F# major LH only
F# major RH only

But the text file reads:

F# major RH only

I want it to look like this:

Db major RH only
F# major LH only
F# major RH only

Answer Source

You are writing and overwriting at the same place in the file because of:
checker.write(Scale + '\n')

chars is set once and is never updated

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download