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

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

    you can compress this into one into two lines of code!!!

    content = open('filepath','r').read().replace('\n',' ')
    print(content)
    

    if your file reads:

    hello how are you?
    who are you?
    blank blank
    

    python output

    hello how are you? who are you? blank blank
    

提交回复
热议问题