python 列表存储为txt文件

l=["A","B","C","D"]
f=open("k1.txt","w")
f.writelines(l)
f.close()
# 输出样式:ABCD

l=["A","B","C","D",1,2,3]
f=open("k2.txt","w")
f.write(str(l))
f.close()
# 输出样式:['A', 'B', 'C', 'D', 1, 2, 3]

l=["A","B","C","D"]
str = '\n'
f=open("k3.txt","w")
f.write(str.join(l))
f.close()
# 如下所示

函数封装:

# 将列表存储为txt格式文件
def list2txt(list, path):
    file = open(path, 'w', encoding="utf-8")
    for l in list:
        l = str(l)  # 强制转换
        if l[-1] != '\n':
            l = l + '\n'
        file.write(l)
    file.close()
    print(f"{path}文件存储成功")

k1.txt:

ABCD

k2.txt:

[‘A’, ‘B’, ‘C’, ‘D’, 1, 2, 3]

k3.txt:

A
B
C
D

你可能感兴趣的:(Python,python)