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

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

You could use:

with open(data.txt, r) as file:
    data = file.read().replace(n, )

Or if the file content is guaranteed to be one-line

with open(data.txt, r) as file:
    data = file.read().rstrip()

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, )

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

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 wont. 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

Leave a Reply

Your email address will not be published. Required fields are marked *