截断“空格”问题x / 002

问题描述 投票:0回答:1
import re
with open("./teste/counter.txt", "r+") as count:
    countread = count.read()

        inputvar = input("Counting - write anything: ")
    if countread == "":
        print("Countread is ''None''. Adding to text file number ''1''.")
        count.write('1')
    else:
        count.truncate(0)
        countread = countread.replace(' ', '')
        countplus = int(countread) + 1
        print(countread)
        count.write(str(countplus))

    count.close()

我正在尝试使用count.truncate(0)删除文件,但是在它添加1之后,在我的文本文件中转到2,在3时出现错误:

ValueError: invalid literal for int() with base 10: '\x002'

对于行“ countplus = ...”

编辑:顺便说一句,“重复读取替换”是解决此问题的一种尝试。

python integer
1个回答
0
投票

已修复此问题

while 3>2:
    with open("./teste/counter.txt", "r+") as count:
        countread = count.read()
        if countread == "":
            countread = "0"
        inputvar = input("Counting " + countread + " write anything: ")
        if countread == "0":
            count.write('1')
        else:
            countplus = int(countread) + 1
            count.truncate(0)
            count.seek(0)
            countread = count.read()
            count.write(str(countplus))

    count.close()
© www.soinside.com 2019 - 2024. All rights reserved.