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

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

    To remove line breaks using Python you can use replace function of a string.

    This example removes all 3 types of line breaks:

    my_string = open('lala.json').read()
    print(my_string)
    
    my_string = my_string.replace("\r","").replace("\n","")
    print(my_string)
    

    Example file is:

    {
      "lala": "lulu",
      "foo": "bar"
    }
    

    You can try it using this replay scenario:

    https://repl.it/repls/AnnualJointHardware

提交回复
热议问题