如何将列表保存到.txt?

时间:2019-05-29 06:11:33

标签: python

我必须将“记录”保存到文本文件中。因此,我尝试使用name_error_record.write( record[0]+" "+record[1]+" "+record[2]+" "+record[3]),但是它不起作用...

我必须对齐为“ No Menu_name Num Total”并将其保存到文本文件中。请帮助。

我要保存的列表是[['No.', 'Menu_name', 'Num', 'Total'], ['4', 'Smoothie_queen', '4', '12000'], ['10', 'Amorparty', '2', '4000'], ['24', 'Plane_yougurt', '14', '49000'], ['36', 'Cofe_latte', '18', '45000'], ['51', 'Cofe_latte', '16', '40000'], ['53', 'Berry_smudie', '17', '51000'], ['54', 'American_air', '4', '8000']]

,并且也必须按“ No Menu name Num Total”按列对齐。 我想我缺少了一些东西,但是找不到它们..帮助T.T

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    errormenu = []
    recordfile = open("ledger_"+date+".txt","r")
    errormenufile = open("menu.txt", "r")

    for error in errormenufile:
        menu = error.split()
        errormenu.append(menu[0])

    errormenufile.close()

    for line in recordfile:
        record = line.split()
        Record.append(record)

        Record = [x for x in Record if errormenu[0] not in x]
        Record = [x for x in Record if errormenu[1] not in x]
        Record = [x for x in Record if errormenu[2] not in x]
        Record = [x for x in Record if errormenu[3] not in x]
        Record = [x for x in Record if errormenu[4] not in x]

    name_error_record = open("ledger_"+date+"_name_error.txt","r")

    for record in Record:
        name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3])

    name_error_record.close()
    #========= STEP 3 ==========

2 个答案:

答案 0 :(得分:1)

只需在以下位置将“ r”更改为“ w”即可:

open("ledger_"+date+"_name_error.txt","r")
open("ledger_"+date+"_name_error.txt","w")

通过设置'w',您可以打开文件进行写入

您可以在以下位置的保存行的末尾添加“ \ n”:

name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3]+'\n')

逐行保存数据

答案 1 :(得分:0)

l=[['No.', 'Menu_name', 'Num', 'Total'], ['4', 'Smoothie_queen', '4', '12000'], ['10', 'Amorparty', '2', '4000'], ['24', 'Plane_yougurt', '14', '49000'], ['36', 'Cofe_latte', '18', '45000'], ['51', 'Cofe_latte', '16', '40000'], ['53', 'Berry_smudie', '17', '51000'], ['54', 'American_air', '4', '8000']]
filename='' # add filenmae
with open(filename, 'w+') as file:
    for i in l:
        file.write('{} {} {} {}\n'.format(*i))