如何修改此循环以更改最后一个打印行?

时间:2013-09-20 07:32:15

标签: python-3.x

def writetofile():
    myFile = open("C:\Jazmyn\myText.txt", "a")
    myFile.write(a)
    myFile.close()

# creating new text file, I have created a folder named "Jazmyn"
# in my C drive and the text file is created there. 


def greenbottles():
    bottle = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight', 'Nine', 'Ten' ]
    text_one = 'green bottles hanging on the wall'
    text_two = 'And if one green bottle should accidentally fall\nThere\'ll be'


for i in range(10, 0, -1):
    with open("C:\Jazmyn\myText.txt","a") as fo:
        print(bottle[i], text_one, file=fo)
        print(bottle[i], text_one, file=fo)
        print(text_two, bottle[i-1], text_one, file=fo)





greenbottles()
# this needs to be written to the file

我需要“一条”线从瓶子换成瓶子,而不是看起来像这样:一个绿色的瓶子挂在墙上 一个绿色的瓶子挂在墙上 至 一个绿色的瓶子挂在墙上 一个绿色的瓶子挂在墙上

是否可以只打印最后一部分并将其写入文件,还是可以修改循环以便更改它?

1 个答案:

答案 0 :(得分:1)

我在想:

def get_text_one(i):
    return "green bottle" + ("" if i == 1 else "s") + " hanging on the wall"

然后而不是:

print(bottle[i], text_one, file=fo)

做的:

print(bottle[i], get_text_one(i), file=fo)

当你有一个动态字符串时,它可能不应该是你声明text_one的“静态”全局变量。