【问题标题】:Printing Loop into a Text file [duplicate]将循环打印到文本文件中[重复]
【发布时间】:2016-02-08 22:41:16
【问题描述】:

我希望能够将其打印到文本文件中,但是我环顾四周,无法弄清楚我需要做什么。

def countdown (n):
    while (n > 1):
        print('\n',(n), 'Bottles of beer on the wall,', (n), 'bottles of beer, take one down pass it around', (n)-1, 'bottles of beer on the wall.')
        n -= 1
        if (n == 2):
            print('\n',(n), 'Bottles of beer on the wall,', (n), 'bottles of beer, take one down pass it around', (n)-1, 'bottle of beer on the wall.')
        else:
            print ('\n',(n), 'Bottle of beer on the wall,', (n), 'bottle of beer, take one down pass it around no more bottles of beer on the wall.')

countdown (10)

【问题讨论】:

  • 我环顾四周,你有什么尝试? SO 不是代码编写服务。请解决您的问题并返回一些代码。
  • 如果你浏览网页来获得这个问题的答案会很好

标签: python file python-3.x text python-3.5


【解决方案1】:

而不是...

...
print('123', '456')

使用...

myFile = open('123.txt', 'w')
...
print('123', '456', file = myFile)
...
myFile.close() # Remember this out!

甚至……

with open('123.txt', 'w') as myFile:
    print('123', '456', file = myFile)

# With `with`, you don't have to close the file manually, yay!

我希望这对你有所启发!

【讨论】:

  • 真的吗?以读取模式打开文件但尝试向其中写入文本?
  • @KevinGuan:哦,对不起。错过了;)。
  • 这实际上为我解决了问题,所以谢谢。
【解决方案2】:

为了更“正确”,它将被视为写入文本文件。您可以编写如下代码:

def countdown (n):
    # Open a file in write mode
    file = open( 'file name', 'w')
    while (n > 1):
        file.write('\n',(n), 'Bottles of beer on the wall,', (n), 'bottles of beer, take one down pass it around', (n)-1, 'bottles of beer on the wall.')
        n -= 1
        if (n == 2):
            file.write('\n',(n), 'Bottles of beer on the wall,', (n), 'bottles of beer, take one down pass it around', (n)-1, 'bottle of beer on the wall.')
        else:
            file.write('\n',(n), 'Bottle of beer on the wall,', (n), 'bottle of beer, take one down pass it around no more bottles of beer on the wall.')

    # Make sure to close the file, or it might not be written correctly.
    file.close()


countdown (10)

【讨论】:

  • 请不要隐藏像file 这样的内置插件。如果没有比“文件”更好的描述,我通常会看到finfoutf
  • @AdamSmith 实际上在 Python 3.x 中有 no file 内置函数。但我同意使用f 而不是file
  • 我不知道有任何内置函数。只是让它更具可读性。我同意将其命名为 f 或其他任何名称。
  • @KevinGuan 我实际上并没有意识到他们在 Python3 中取消了它(无论如何我从来没有找到它的好用处)。感谢您的提醒
  • @AdamSmith 是的,here 是一个很好的问题 :)
猜你喜欢
  • 2016-07-27
  • 1970-01-01
  • 2013-10-28
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多