我不能让列表写成txt (python)

I cannot let the list write in txt (python)

我想用writelines()让list写成txt,可是运行之后我的txt里什么都没有了。我的代码有什么问题?

如果可以,请帮助我。谢谢!

示例列表(记录):[['flower', '200'], ['ham', '60'], ['van', '150']]

我想在txt中这样写:

花200朵

火腿 60

面包车 50

我的代码:

def save(initial_money, records): # I need both so don't change.
    with open('records.txt', 'w') as f: 
        first_line = str(initial_money) + "\n"
        f.write(first_line)
        return initial_money
        L = []
        for rec, amt in records:
            all_rec = str(rec) + " " + str(amt) + "\n"
            L.append(all_rec)
        f.writelines(records) # must use writelines
        return records

应该这样做:

def save(initial_money, records):
    with open('records.txt', 'w') as f: 
        first_line = str(initial_money) + "\n"
        f.write(first_line)
        for rec, amt in records:
            f.write(str(rec) + " " + str(amt) + "\n")

第一个 return 关闭函数,您也不需要第二个 return,records 可用作参数。

如果你坚持使用writelines,你可以修改如下:

def save(initial_money, records):
    with open('records.txt', 'w') as f: 
        first_line = str(initial_money) + "\n"
        f.write(first_line)
        L = []
        for rec, amt in records:
            L.append(str(rec) + " " + str(amt) + "\n")
        f.writelines(L)

我没有成功理解你需要两个参数。

这是我的代码:

def save(initial_money,records):
    first_line = str(initial_money) + "\n"
    with open('records.txt', 'w') as f:
        f.writelines(first_line)
        for items in records:
            f.writelines(f"{items[0]} {items[1]} ")
            f.writelines('\n')

records = [['flower', '200'], ['ham', '60'], ['van', '150']]
initial_money = 0
save(initial_money, records)