python-3.x - 更改文本文档的值时遇到问题

标签 python-3.x

我试图打开一个名为“rows.txt”的文件,并在每次运行代码时将值更改为 + 1。

exel_rows = open("Rows.txt", "r")

  exel_rows = exel_rows + 1

  exel_rows = str(exel_rows)

  saveFile = open('Rows.txt', 'w')
  saveFile.write(exel_rows)
  saveFile.close()

错误代码是:

Traceback (most recent call last):
  File "C:\Users\Fletcher\Desktop\Bank.py", line 158, in <module>
    exel_rows = exel_rows + 1
TypeError: unsupported operand type(s) for +: '_io.TextIOWrapper' and 'int'

最佳答案

我认为您正在将数字添加到字符串中。所以尝试下面的代码,int() 会将字符串转换为整数。

此外,您还必须使用.read()来读取文件数据并将其存储在变量内容中。

  exel_rows = open("Rows.txt", "r")
  exel_rows = exel_rows.read();
  exel_rows = int(exel_rows) + 1
  exel_rows = str(exel_rows)
  saveFile = open('Rows.txt', 'w')
  saveFile.write(exel_rows)
  saveFile.close()

关于python-3.x - 更改文本文档的值时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54740690/

相关文章:

python - 在同一程序中使用 Python 2 和 3 库的正确方法(如果有)是什么?

python - python 类中的所有方法都表现得像静态

python - 令人困惑的变量作用域(来自外部作用域的隐藏变量)

python - 为什么这个if语句不执行?

python - 将字符串格式的方程转换为 Line(geometry) 对象

python - 为什么 python 假设我的路径是项目根目录,这是两个目录级别?

python - 为什么无参数函数调用执行得更快?

python - 从函数返回数组索引

python - 正确输入 sys.stdout 和文件

python - ValueError : not enough values to unpack (expected 2, 得到 1) NetworkX python 3