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

前端 未结 23 2407
醉酒成梦
醉酒成梦 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:05

    Try the following:

    with open('data.txt', 'r') as myfile:
        data = myfile.read()
    
        sentences = data.split('\\n')
        for sentence in sentences:
            print(sentence)
    

    Caution: It does not remove the \n. It is just for viewing the text as if there were no \n

提交回复
热议问题