简体   繁体   中英

How to save the list in to .txt?

I have to save 'Record' into text file. So I have tried to use name_error_record.write( record[0]+" "+record[1]+" "+record[2]+" "+record[3]) but it doesn't work...

I have to align as 'No Menu_name Num Total' and save it into text file. please help..

The list that I have to save is [['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']]

and also it has to be aligned by columns as 'No Menu name Num Total'. I think I am missing something but I can't find them.. help TT

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 ==========

Simply change 'r' to 'w' in:

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

by setting 'w' you open file for writing

you can add '\\n' at the end of saved line in:

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

to save data line by line

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM