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

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

    I don't feel that anyone addressed the [ ] part of your question. When you read each line into your variable, because there were multiple lines before you replaced the \n with '' you ended up creating a list. If you have a variable of x and print it out just by

    x

    or print(x)

    or str(x)

    You will see the entire list with the brackets. If you call each element of the (array of sorts)

    x[0] then it omits the brackets. If you use the str() function you will see just the data and not the '' either. str(x[0])

提交回复
热议问题