用python编写文本文件中的列表

2024-10-03 09:19:10 发布

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

我编写此代码是为了将列表的内容写入文本文件

    
    def writefile(daymonths):                                    
    filename = "/Users/admin/Documents/Month.txt"
    outputfile = open(filename, "w")
    months = ["{}\n".format(month) for month in daymonths]
    outputfile.writelines(months)
    outputfile.close()

但该文件只显示最后一项,我尝试使用outputfile.write(),但仍然没有显示整个列表。 文本文件屏幕截图如下 file contents goes here to see.


Tags: 代码内容列表admindeffilenameusersdocuments
1条回答
网友
1楼 · 发布于 2024-10-03 09:19:10

代码中存在缩进错误。如果writelines()不起作用,则尝试使用for循环。写入时间为u,以月为单位,outputfile.Write(u)。您的代码:

def writefile(daymonths):                                    
    filename = "/Users/admin/Documents/Month.txt"
    outputfile = open(filename, "a")
    months = ["{}\n".format(month) for month in daymonths]
    for i in months:
        outputfile.write(i)
    outputfile.close()

相关问题 更多 >