使用文件名和列表作为参数将列表写入文件函数

Writing a list to file function with filename and list as parameter

我正在尝试编写一个如下所示的函数,但它会将列表和文件名作为参数。这是令人讨厌的基本但它逃脱了我。

def write_list_to_file():
    wordlst = ["No", "Time", "for", "this"]
    file = open(filename, 'w')
    for items in wordlst:
        file.writelines(items + '\n')
    file.close()wordlst

鉴于这有效,这:

def write_list_to_file(wordlst, filename):
    wordlst = ["No", "Time", "for", "this"]
    with open(filename+".txt",'w') as file:
        for items in wordlst:
            file.writelines(items + '\n')

应该也是。除了以 write_list_to_file(wordlst, Idk) returns 的方式调用函数外,没有文件。完全意识到列表保持静态我已经以相同的方式尝试了一个参数函数,即:

def makefile(filename):
    file = open(filename + ".txt", 'w')
    file.close()

makefile("Really")

这也不会以某种方式产生任何文件。请忽略列表的元素,我在这方面的时间比我愿意承认的要长得多,而且我找不到有助于解决这个特定问题的东西。我找到了无数的解决方案来实现这一点,但不是采用将任何列表和任何文件作为输入的函数形式。在每种情况下,退出代码都没有显示错误,所以我至少希望创建一个文件但找不到任何文件。

TLDR:尝试创建一个 write_list_to_file(wordlst,filename) 函数,一定是明显遗漏了,感谢帮助。

编辑:已批准,缩进问题仅在此 post 不过,代码缩进正确,匆忙完成

Edit2:cf 评论

您的代码示例没有正确的缩进,这在编写 python 代码时很重要。

此外,writelines() 接受一个字符串列表。您遍历列表并希望将每个元素保存在单独的行中 - write() 将是正确的函数。

最后,确保将文件名作为字符串传递。

此代码应该有效:

def write_list_to_file(wordlst, filename):
    with open(filename + '.txt', 'w') as file:
        for item in wordlst:
            file.write(item + '\n')

write_list_to_file(['element1', 'element2', 'element3'], 'tempfile')