将列表保存到.txt文件中,并将其从文件读回lis

2024-04-24 23:45:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力将一个列表保存到一个.txt文件中,然后从.txt文件读回Python中的列表。在

这是我的名单

SS1=[(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 5, 6), (1, 2, 4, 5, 6), (1, 3, 4, 5, 6), (2, 3, 4, 5, 6)]

以可读格式逐行保存每个元组到ABC.文本…不是ascii或加密的。在

需要另一个例行程序来阅读ABC.文本回到Python中的列表中。在

这是我的代码,我无法读取记事本上的物理文件

^{pr2}$

Tags: 文件代码文本txt列表格式ascii物理
3条回答

你可以试试这样的方法:

SS1=[(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 5, 6), (1, 2, 4, 5, 6), (1, 3, 4, 5, 6), (2, 3, 4, 5, 6)]

def write_to_txt(a, file_name, delimiter=','):
    with open(file_name, 'a') as f:
        for k in a:
            fmt = '%s' % delimiter
            f.write(fmt.join(map(str, k)) + '\n')

def read_from_txt(file_name):
    with open(file_name, 'r') as f:
        data = [tuple(map(int, k.split(','))) for k in f.read().splitlines()]
    return data

write_to_txt(SS1, 'ABC.txt')
data  = read_from_txt('ABC.txt')
print(data)

这应该可以做到:

SS1=[(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 5, 6), (1, 2, 4, 5, 6), (1, 3, 4, 5, 6), (2, 3, 4, 5, 6)]
with open('newfile.txt','w') as fileobj:
        fileobj.write('\n'.join('%s' % (x,) for x in SS1))

为的创建一个文件对象fileobj新文件.txt'使用w(写入模式)

Make a singleton tuple with our as the only item, i.e. the (thetuple,) and write it in the file.

只需使用numpy

import numpy as np
SS1 = [(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 5, 6), (1, 2, 4, 5, 6), (1, 3, 4, 5, 6), (2, 3, 4, 5, 6)]
np.savetxt('my_file.txt', SS1)
my_new_SS1 = np.genfromtxt('my_file.txt')
print(my_new_SS1)


Out[1]: [[ 1.  2.  3.  4.  5.]
        [ 1.  2.  3.  4.  6.]
        [ 1.  2.  3.  5.  6.]
        [ 1.  2.  4.  5.  6.]
        [ 1.  3.  4.  5.  6.]
        [ 2.  3.  4.  5.  6.]]

相关问题 更多 >