【问题标题】:Writing random numbers to a Python file and using newline to concatenate将随机数写入 Python 文件并使用换行符连接
【发布时间】:2013-12-11 20:07:07
【问题描述】:

此程序生成用户定义数量的随机数,然后写入文件。该程序在编写时工作正常,但我希望文本文件使用 \n 连接。我做错了什么?

#这个程序写入用户定义 #随机数到文件中

import random

randfile = open("Randomnm.txt", "w" )

for i in range(int(input('How many to generate?: '))):
    line = str(random.randint(1, 100))
    randfile.write(line)
    print(line)

randfile.close()

【问题讨论】:

  • '\n'.join(str(randint(1,100)) for _ in range(int(input())))
  • @roippi:最后一个换行符没有了。您可以在最后添加它,但在这种情况下,为什么不直接使用 randfile.writelines(str(randint(1,100))+'\n' for _ in range(int(input()))) 并完全避免使用 join

标签: python file-io newline


【解决方案1】:

添加“\n”:

import random

randfile = open("Randomnm.txt", "w" )

for i in range(int(input('How many to generate?: '))):
    line = str(random.randint(1, 100)) + "\n"
    randfile.write(line)
    print(line)

randfile.close()

【讨论】:

    【解决方案2】:

    您还可以使用 Python 3 的 print 函数的 file 关键字参数:

    import random
    
    with open("Randomnm.txt", "w") as handle:
        for i in range(int(input('How many to generate?: '))):
            n = random.randint(1, 100)
    
            print(n, file=handle)
            print(n)
    
    # File is automatically closed when you exit the `with` block
    

    【讨论】:

      【解决方案3】:

      file.write() 只是将文本写入文件。它不会连接或附加任何内容,因此您需要自己附加一个\n

      (请注意,该类型在 Python 3 中将称为 _io.TextIOWrapper

      要做到这一点,只需替换

      line = str(random.randint(1, 100))
      

      line = str(random.randint(1, 100))+"\n"
      

      这将为每个随机数添加一个换行符。

      【讨论】:

      • 我很确定这是 Python 3.x(参见 inputraw_inputprint 作为函数),所以没有像 file 这样的类型;它实际上是像io.TextIOWrapper.write 这样丑陋的东西,它只是继承了io.TextIOBase.write。 (不幸的是,3.x 没有任何更简单的“文件对象”文档。)但除此之外,很好的解释。
      • @abarnert:谢谢,补充了。
      猜你喜欢
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2021-02-15
      • 2012-01-19
      • 1970-01-01
      相关资源
      最近更新 更多