How to read a text file into a string variable and strip newlines?

前端 未结 23 2571
醉酒成梦
醉酒成梦 2020-11-22 05:47

I use the following code segment to read a file in python:

with open (\"data.txt\", \"r\") as myfile:
    data=myfile.readlines()

Input fil

23条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 06:23

    Regular expression works too:

    import re
    with open("depression.txt") as f:
         l = re.split(' ', re.sub('\n',' ', f.read()))[:-1]
    
    print (l)
    

    ['I', 'feel', 'empty', 'and', 'dead', 'inside']

提交回复
热议问题