从单词列表中将句子写入文本文件 - python

时间:2013-12-09 14:49:22

标签: python

我有一个单词列表,当组合成一个句子。我想将此列表写入文本文件,但是,目前列表是垂直输出的。

例如:

word_list = [“the”,“winter”,“is”,“beautiful”]

目前输出是......

the
winter
is
beautiful

而我希望它是

the winter is beautiful.

我的代码:

def WriteToTextfile(list_to_write):
    new_writefile = open("text.txt","w")
    for k in list_to_write:
        new_writefile.write("%s\n" % k)
    new_writefile.close()

4 个答案:

答案 0 :(得分:3)

只需加入这样的字样然后再写

new_writefile.write(" ".join(list_to_write))

使用文件时始终使用with

with open("text.txt", "w") as new_writefile:
    new_writefile.write(" ".join(list_to_write))

答案 1 :(得分:3)

您正在明确添加“\ n”字符,只需将其删除

即可
def WriteToTextfile(list_to_write):
    new_writefile = open("text.txt","w")
    for k in list_to_write:
        new_writefile.write("%s " % k)
    new_writefile.close()

答案 2 :(得分:2)

在将列表写入文件之前加入列表,如下所示:

" ".join(list_to_write

并使用with语句编写如下:

with open("text.txt","w") as new_writefile:

答案 3 :(得分:1)

def WriteToTextfile(list_to_write):
    with open('text.txt', 'wb') as fp:
        fp.write('%s.' % (' '.join(list_to_write),))