Categories
Python Answers

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

Spread the love

Sometimes, we want to read a text file into a string variable and strip newlines with Python.

In this article, we’ll look at how to read a text file into a string variable and strip newlines with Python.

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

To read a text file into a string variable and strip newlines with Python, we can open the file with open.

Then we read the opened file with read into a string.

And then we call the string’s replace method to replace the new lines.

For instance, we write:

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

to open the file with open by calling it with the path and the 'r' read permission to read the file.

Then we call the opened file‘s read method to read the file into a string.

And finally, we call replace with '\n' and '' to replace the newline characters with empty strings and assign the returned strings with data.

Therefore, data is 'foobarbaz' if data.txt has:

foo
bar
baz

Conclusion

To read a text file into a string variable and strip newlines with Python, we can open the file with open.

Then we read the opened file with read into a string.

And then we call the string’s replace method to replace the new lines.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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