Python-使用变量作为名称

时间:2015-05-26 04:42:33

标签: python text-files filenames

所以我正在做一个项目,我的程序创建一个名为" Ten Green Bottles"并在其中写下10个绿瓶装的歌曲,我已经成功地使它工作但我想让它变得更好。我开始向用户提供可选的瓶子数量,并且工作正常。现在我只想让名字与用户输入的瓶子量相关。也就是说,如果我放入20瓶,我希望文本文件的名称为" Twenty Green Bottles"而不是"十个绿瓶" 代码:

num1=int(input('Pick a number between 10 and 30: '))

def main():
    numbers =[ 'no', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven',      'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen',     'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty', 'Twentyone',      'Twentytwo', 'Twentythree', 'Twentyfour', 'Twentyfive', 'Twentysix',         'Twentyseven', 'Twentyeight', 'Twentynine', 'Thirty' ]
text_one = 'green bottle%s\nHanging on the wall'
text_two = "\nAnd if one green bottle\nShould accidentally fall\nThere'll be"
text_three =' \n'


with open( 'Green Bottles.txt', 'w') as a:
    for l in range(num1, 0, -1):
        a.write(numbers[l]+ ' ')
        if l == 1:
            a.write(text_one % '' +'\n')
        else:
            a.write(text_one % 's' +'\n')

        a.write(numbers[l] + ' ')
        if l == 1:
            a.write(text_one %  '' + '\n') 
        else:
            a.write(text_one % 's' +  '\n')
        a.write(text_two + ' ')
        a.write(numbers[l-1] + ' ')
        if (l - 1) ==1 :
            a.write(text_one % ''+'\n')
        else:
            a.write(text_one % 's'+'\n')
        a.write('\n' + '\n')



if __name__ == '__main__':
main()

3 个答案:

答案 0 :(得分:2)

您可以将该文件的名称提供给函数并返回该文件。

def write(nameOfFile):
    print('Creating new text file') 

    name = nameOfFile+'.txt'  # Name of text file coerced with +.txt

    try:
        file = open(name,'r+')   # Trying to create a new file or open one
        return file

    except:
        print('Something went wrong! Can\'t tell what?')
        sys.exit(0) # quit Python

a = write(numbers[num1] )

答案 1 :(得分:2)

替换此行:

with open( 'Green Bottles.txt', 'w') as a:

使用

with open(numbers[num1] + ' Green Bottles.txt', 'w') as a:

这将在您的文件名前添加适当的单词。

答案 2 :(得分:1)

您可以使用字符串格式

将输入添加到文件名

使用

with open('%s Green Bottles.txt' % numbers[num1], 'w') as a: