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

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

    In Python 3.5 or later, using pathlib you can copy text file contents into a variable and close the file in one line:

    from pathlib import Path
    txt = Path('data.txt').read_text()
    

    and then you can use str.replace to remove the newlines:

    txt = txt.replace('\n', '')
    

提交回复
热议问题