首页 > 解决方案 > 截断“空格”问题 x/002

问题描述

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 = ...''

编辑:顺便说一下,''countread replace'' 是为了解决这个问题。

标签: pythoninteger

解决方案


用这个修复它

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()

推荐阅读