为什么python用乱码字符写入文件

K D*_*awG 3 python character-encoding

我 在项目euler尝试了问题10并且通过但是我决定,如果我将所有低于200万的素数用于文本(.txt)文件,那么我继续并且因此对主函数进行了一些小的调整以解决问题因此,如果不将其添加到变量(tot),我将生成器生成的素数写入文本文件,并且它最初工作但忘记在每个素数后添加空格,因此输出有点乱码

357111317192329313741434753

所以我修改了我txt.write(str(next_prime))txt.write(str(next_prime) + ' ')

在稍作修改后,输出完全是胡言乱语

"`‷ㄱㄠ"㜱ㄠ<㌲㈠<ㄳ㌠‷ㄴ㐠"

这是我的功能完整代码:

def solve_number_10():
    total = 2
    txt = open("output.txt","w")
    for next_prime in get_primes(3):
        if next_prime < 2000000:
            txt.write(str(next_prime) + ' ')
            #total += next_prime
        else:
            print "Data written to txt file"
            #print total
            txt.close()
            return
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况,我怎样才能使输出像

3 5 7 11 13 17 19
Run Code Online (Sandbox Code Playgroud)

Die*_*Epp 11

这是Microsoft的记事本程序中的错误,而不是您的代码中的错误.

>>> a = '???????‹??‹?????'
>>> a.decode('UTF-8').encode('UTF-16LE')
'5 7 11 13 17 19 23 29 31 37 41 4'
Run Code Online (Sandbox Code Playgroud)

哦,嘿,看,他们是素数(我假设4只是截断43).

您可以在记事本中解决该错误

  1. 使用没有错误的其他文件查看器.

  2. 将ZWNBSP写入文件的开头一次,以UTF-8编码:

    txt.write(u'\uFEFF'.encode('UTF-8'))
    
    Run Code Online (Sandbox Code Playgroud)

    这被错误地称为BOM.它将是UTF-16的BOM,但从技术上讲,UTF-8不具备BOM.大多数程序忽略它,而在其他程序中它将是无害的.