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

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

    python3: Google "list comphrension" if the square bracket syntax is new to you.

     with open('data.txt') as f:
         lines = [ line.strip( ) for line in list(f) ]
    

提交回复
热议问题