简体   繁体   English

如何序列化列表并将其写入 Python 中的 txt 文件

[英]How to serialize a list and write the same to a txt file in Python

a Python newbie here.一个 Python 新手在这里。 Im learning Python and stuck at the below problem.我正在学习 Python 并陷入以下问题。 I want my output file to be serialized.我希望对我的 output 文件进行序列化。 Please help.请帮忙。

#say the list is l = ['h','e','l','l','o']
filename = input("Input File name: ")
with open(filename+".txt",'w') as f:
    for items in l:
        f.write(f"{items}\n")

How do I add serial numbers to my output.如何将序列号添加到我的 output。 I know to enumerate but how to add enumerate to the output file.我知道枚举但如何将枚举添加到 output 文件中。

l = ['h','e','l','l','o']
filename = input("Input File name: ")
with open(filename+".txt",'w') as f:
    for index,items in enumerate(l,1):
        f.write(f"{index} {items}\n")

In enumerate first parameter is the iterable that is l and second parameter is from where you want to start your index在枚举中,第一个参数是 l 的可迭代对象,第二个参数是您要开始索引的位置

Just do this:-只需这样做:-

for i in range(len(l)):
    f.write(f'{i+1}.{l[i]}\n')        #l here is your list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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