从txt读取时如何绑定行尾和行首?

时间:2016-12-30 18:23:58

标签: python

我有这样的txt,我从txt文件中读到了这个。

that's mai purpose! in order not to.
go and.. ll' be in h'van,. 

我想创建一个这样的列表:["that's","mai","purpose!","in","order","not","to.\ngo","and..","ll'","be","in","h'van,."]

我尝试split()但是它有效,直到\n部分我该怎么处理它?困难的部分是“to.\ngo”谢谢!

2 个答案:

答案 0 :(得分:0)

您需要调用file.read()将所有内容作为单个字符串获取,然后调用str.split将这些字词拆分为:

with open('/path/to/file.txt') as f:
    my_file_str = f.read()
    my_list = my_file_str.split(' ')
    #         split on space ' ' ^

答案 1 :(得分:0)

试试这个:

with open("c.txt") as f:
     lines = f.read()
     mlist = lines.strip().split(' ')
print mlist

输出:

["that's", 'mai', 'purpose!', 'in', 'order', 'not', 'to.\ngo', 'and..', "ll'", 'be', 'in', "h'van,."]