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

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

    I have fiddled around with this for a while and have prefer to use use read in combination with rstrip. Without rstrip("\n"), Python adds a newline to the end of the string, which in most cases is not very useful.

    with open("myfile.txt") as f:
        file_content = f.read().rstrip("\n")
        print file_content
    

提交回复
热议问题