snippetpythonCritical
How can I read a text file into a string variable and strip newlines?
Viewed 0 times
howreadnewlinesintovariableandcanstriptextfile
Problem
I have a text file that looks like:
How can I read the file into a single-line string without newlines, in this case creating a string
For reading the file into a list of lines, but removing the trailing newline character from each line, see How to read a file without newlines?.
ABC
DEFHow can I read the file into a single-line string without newlines, in this case creating a string
'ABCDEF'?For reading the file into a list of lines, but removing the trailing newline character from each line, see How to read a file without newlines?.
Solution
You could use:
Or if the file content is guaranteed to be one line:
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()Code Snippets
with open('data.txt', 'r') as file:
data = file.read().replace('\n', '')with open('data.txt', 'r') as file:
data = file.read().rstrip()Context
Stack Overflow Q#8369219, score: 1978
Revisions (0)
No revisions yet.