"Python只向最后一个输出写入文件"

2024-10-01 00:15:08 发布

您现在位置: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()

我的输出如下:

^{pr2}$

但文本文件显示:

F# major RH only

我希望它看起来像这样:

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

Tags: thetoinforifaswithline
1条回答
网友
1楼 · 发布于 2024-10-01 00:15:08

代码在输出文件中的同一位置写入和重写。这是由于:

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

chars设置一次,从不更新

相关问题 更多 >