Python-创建一个以变量为名称的文本文件 [英] Python- creating a text file with a variable as a name

查看:465
本文介绍了Python-创建一个以变量为名称的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在做一个项目,其中我的程序创建了一个名为十个绿色瓶子"的文本文件,并在其中写入了10个绿色瓶子的歌曲,我已经成功地使它工作了,但我想做得更好.我首先将瓶的数量设置为用户可选,并且效果很好.现在我只希望名称与用户输入的瓶子数量有关.即,如果我放入20瓶,我希望文本文件的名称为二十绿色瓶",而不是十绿色瓶" 代码:

So im doing a project where my program creates a textfile named "Ten Green Bottles" and writes the 10 green bottles song in it, I have successfully got it working but i want to make it better. I started by making the amount of bottles optional to the user and it worked fine. Now i just want the name to be relevent with the amount of bottles input by the user. ie, if I put in 20 bottles i want the name of the text file to be "Twenty Green Bottles" rather than "Ten Green Bottles" Code:

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()

推荐答案

替换此行:

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

使用

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

这将在文件名前加上适当的单词.

This will prepend your file name with the appropriate word.

这篇关于Python-创建一个以变量为名称的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆