【问题标题】:Writing Integers to a text file将整数写入文本文件
【发布时间】:2017-02-23 12:39:36
【问题描述】:

Python 新手,我正在将整数写入程序的文本文件,但是一旦数字超过 10,程序就无法工作。因此,我想在每个整数之后添加一个空格,我尝试了几种方法来做到这一点,但它没有奏效。

这是我尝试这样做的一种方式:

positions = int(uq_words.index(i) + 1, (" "))

我添加了(" ")

我意识到这可能是一个真正需要解决的基本问题。

【问题讨论】:

  • 不清楚你想要什么。要写入文件,请使用 with open('filename', 'w') as f: 然后 f.write('whatever you want to write')
  • 啊,我想写入变量 positions 的内容 - 但是,每当我尝试将整数写入文本文件时,我都会收到错误消息 TypeError: 'str' object cannot be interpreted as an integer 我不确定如何解决这个问题。
  • 您需要了解string formatting。另请参阅docs.python.org/3/tutorial/… 但同时您可以执行positions = str(uq_words.index(i) + 1) + ' ',假设uq_words.index(i) + 1 是您要打印或保存到文件的整数,那么positions 将包含所需的字符串。
  • a=2 这是整数; str(a) 将变成字符串;您可以使用 type() 函数进行检查

标签: python python-3.x text text-files


【解决方案1】:

尝试类似" ".join(uq_words) 然后写入文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    相关资源
    最近更新 更多