如何在Python 3中从文本文件制作字符串?

时间:2018-07-18 18:36:07

标签: python

path = "C:\\Users\\user\\Downloads\\wordlist.txt"
word_list = open(path, 'r')
list = [x for x in word_list.split(" ")]

如何打开文件,以便可以将其制成字符串,然后最终将该字符串转换为列表?我尝试过使用split(),但似乎文本文件不能被拆分,尽管它们可以被读取。

2 个答案:

答案 0 :(得分:2)

使用with open

例如:

path = "C:\\Users\\user\\Downloads\\wordlist.txt"
l = []
with open(path, "r") as infile:    #Read file
    for line in infile:            #Iterate over each line
        l.append(line.split())     #split by space and append

答案 1 :(得分:0)

word_list.readlines()将根据行结尾给出列表本身