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

Leave a Comment