【问题标题】:The print of while loop into text filewhile循环打印到文本文件中
【发布时间】:2016-07-27 12:01:49
【问题描述】:

我已经在 python 中完成了这个。当我插入一个单词时,它会在一个数字后重复 例如,如果我插入堆栈,它将打印:

stack 1
stack 2
stack 3
stack 4
stack 5
stack 6
stack 7
stack 8
stack 9

我希望 python 打印文件文本中的名称和数字。我搜索但没有找到任何东西。

代码:

pwd=raw_input("Enter a word:")
n=0
n=str(n)
print (pwd,n)
while n<9:
  out_file=open("tesxt.txt","w")
  n+=1
  out_file.write(pwd)
  out_file.write(n)
out_file.close()

我希望 python 编写从循环生成的单词。 谢谢帮忙

【问题讨论】:

    标签: python python-2.7 loops python-3.x while-loop


    【解决方案1】:

    在 Python 2.7 中首先使用 print 不带括号:

    >>> print "hello world"
    hello world
    

    那么你应该在while循环之外打开文件。

    out_file = open("test.txt", "w")
    i = 0
    while n < 9:
       # do something here  
    
    out_file.close()
    

    【讨论】:

      【解决方案2】:

      您的问题在于重新定义 n。你从 n 作为整数 (n = 0) 开始,然后将其转换为字符串 (n = str(n))。

      试试这个:

      pwd = raw_input("Enter a word: ")
      n = 0
      print("{} {}".format(pwd, n))
      with open("test.txt", "w") as out:
          while n < 9:
              out.write("{} {}\n".format(pwd, n))
              n += 1
      

      这应该会给您期望的输出,因为您永远不会重新定义 n。 如果您想同时兼容 python 2 和 3,请将 from __future__ import print_statement 添加到脚本顶部,这将使您的 print() 调用正常工作。

      【讨论】:

        【解决方案3】:

        你有几个错误:

        1. 您尝试在 str 对象上 += 1。这是不行的。
        2. 您多次打开一个文件却没有关闭它。

        尝试利用 open 使用的上下文管理器和内部的 while 循环。像这样的:

        pwd = raw_input("Enter a word: ")
        with open("tesxt.txt", "w") as fout:
            n = 0
            while n <= 9:  # this will print 0-9. without the =, it will print 0-8
                data = "{} {}".format(pwd, n)
                print(data)
                fout.write("{}\n".format(data))
        

        【讨论】:

          【解决方案4】:

          pwd = raw_input('输入一个单词:')
          n = 0
          打印密码,n
          使用 open('tesxt.txt','w') 作为 out_file:
          而 n n += 1
          out_file.write('{} {}\n'.format(pwd, n))

          【讨论】:

          • 如果我想列出姓名... 我该怎么办?我是python的初学者
          猜你喜欢
          • 2014-06-16
          • 2016-02-08
          • 2017-04-23
          • 2016-03-24
          • 1970-01-01
          • 1970-01-01
          • 2015-05-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多