写入文件时弹出奇怪字符

Odd character popping up when writing to a file

python 的新手。我正在测试文件,并试图将一个数字(作为原始输入)写入文件。然后我想要一个函数来将这个数字作为输入参数并用它执行方程式。

但是由于某种原因,写入文件时会弹出一个奇怪的字符。当我试图复制粘贴它来查找它时,它只是复制为这个奇怪的数字块或一个空的 space。 weird character in notepad

到目前为止,这是我的代码:

def function(x):
    y = x + 1
    return y

Input = raw_input('Number?')

with open('in_test.txt','w+') as inFile_test:
    inFile_test.write(Input)
    lines = inFile_test.readline()
    lines_int = [int(x) for x in lines.split()]
    print str(lines_int)

f_test = function(lines_int)
print str(f_test)

我也尝试过将文件格式更改为 r+,在记事本 (ANSI) 中检查编码类型,并查找出现的错误。

    lines_int = [int(x) for x in lines.split()]
ValueError: invalid literal for int() with base 10: '\x02'

我假设错误是由奇怪的字符引起的,但我不确定是什么导致了奇怪的字符。

您需要将文件指针重置回开头。 您可以使用 tell() 函数检查文件指针的当前位置。

with open('in_test.txt','w+') as inFile_test:
    inFile_test.write(Input)
    print inFile_test.tell()
    inFile_test.seek(0) # re-position the file pointer to the beginning
    lines = inFile_test.readline()
    lines_int = [int(x) for x in lines.split()]
    print str(lines_int)

此外,对 function() 的调用不正确,您已将其定义为接受 int,但使用列表参数调用它。