我试图打开一个名为“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/