2016-08-29 90 views
1

我想寫一個程序,選擇一個隨機的音階,直到所有被選中,我遇到的問題是我的代碼只寫一行到我的文本文件。python只寫最後輸出到文件

我知道這是與Python: Only writes last line of output類似的問題,但我已經嘗試瞭解決方案來打開並關閉循環外的文件(至少是我的能力最好,如果我錯了,請糾正我) 。

我的代碼是這樣的:

#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: 
      break 

    #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 

    '''HERE IS WHERE I BELIEVE I FOLLOWED THE LINKED QUESTION''' 
    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 
      Scale=str(MajorScalesHandsSeparate[ScalePicker]) 
      checker.seek(chars) 
      checker.write(Scale + '\n') 

      #prints chosen scale 
      print MajorScalesHandsSeparate[ScalePicker] 

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

      #removes item from list  
      else: 
       MajorScalesHandsSeparate.remove(MajorScalesHandsSeparate[ScalePicker]) 
       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 
    checker.close() 

#calls the function 
MajorScalesHandsSeparate() 

我的輸出是這樣的:

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

但文本文件讀取:

F# major RH only 

我希望它看起來是這樣的:

Db major RH only 
F# major LH only 
F# major RH only 
+0

讀取文件而寫它是不是很好。如果MajorScalesHandsSeparate [ScalePicker]不在打開狀態('MajorScalesHandsSeparate.txt')。read()' –

+0

55和56行有縮進錯誤。 –

+0

@ Jean-FrançoisFabre所以我應該再次打開文件以寫入它? – trunting

回答

1

代碼在輸出文件的相同位置寫入和覆蓋。這是由於:

checker.seek(chars) 
checker.write(Scale + '\n') 

chars設置一次,從不更新

+0

非常感謝:) – trunting