我能使用用户定义的函数写入文件吗?

时间:2013-09-18 01:08:47

标签: 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):
        print(bottle[i], text_one)
        print(bottle[i], text_one)
        print(text_two, bottle[i-1], text_one)


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

我是python的新手,我发现很难。有可能使greenbottles代码可以写入新文本文件(myText),还是可以修复print语句以便写入文件?

1 个答案:

答案 0 :(得分:0)

print takes a file keyword-only parameter,所以如果您只需要将要在for循环中打印的值写入文件,您只需打开一个文件(或类似文件的对象)并将其传递给印刷:

with open("your/file.ext", "a") as fo:
    print("Hello", file=fo)
    print("All this goes to fo", file=fo)