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

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

    You can read from a file in one line:

    str = open('very_Important.txt', 'r').read()
    

    Please note that this does not close the file explicitly.

    CPython will close the file when it exits as part of the garbage collection.

    But other python implementations won't. To write portable code, it is better to use with or close the file explicitly. Short is not always better. See https://stackoverflow.com/a/7396043/362951

提交回复
热议问题