Python 3.x 在pickle.damp将列表转换为txt后,会出现一些奇怪的字符

Python 3.x 在pickle.damp将列表转换为txt后,会出现一些奇怪的字符,python-3.x,Python 3.x,调用后,all.txt为: 欧元]q(X aaaqX bbbqX cccqe 这些奇怪的字符,如€]q(X)从何而来?如何消除它们?pickle.dump用于python对象,它包含一些元信息。如果您将字符串写入all.txt,下面的代码就是这样做的,举个例子 import pickle new = open("all.txt", "wb") files = ["aaa", "bbb", "ccc"] def toTxt(dir): global new pickle.dump(

调用后,all.txt为:

欧元]q(X aaaqX bbbqX cccqe


这些奇怪的字符,如€]q(X)从何而来?如何消除它们?

pickle.dump
用于python对象,它包含一些元信息。如果您将字符串写入all.txt,下面的代码就是这样做的,举个例子

import pickle
new = open("all.txt", "wb")
files = ["aaa", "bbb", "ccc"]
def toTxt(dir):
    global new
    pickle.dump(files, new)
    new.close()        

dir = "C:\\python36\\captions"
toTxt(dir)
import os
files = ["aaa", "bbb", "ccc"]

def toTxt(dir):
    fname = os.path.sep.join([dir, "all.txt"])
    with open(fname, "wb") as f:
        for file in files:
            f.write(file.encode('utf-8'))

dir = "." # current directory
toTxt(dir)