-2

I am trying to read file without modifying the text format and then store it in variable so that I can perform Regex on it. I tried the following code

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

And it stores text like this: first_output

But I want to store text in a variable data like this: required_output

How can I achieve this, I search for many tutorials, blogs but couldn't find the exact solution.

Tech Geek
  • 1
  • 2
  • Try `print(data)`. – 9769953 Aug 17 '22 at 09:06
  • Note that the data *is stored* as is. See all those newline characters, `\n`? Those are the line breaks in your required_output. The required_output is just a *rendering* of the data, not the actual data. – 9769953 Aug 17 '22 at 09:07
  • You're confusing the _representation_ of the string with the _content_ of the string. The variable contains exactly the data you want. – Matthias Aug 17 '22 at 09:38

1 Answers1

0

Note that line breaks/starting a new line is stored by python/programs as \n.

Perhaps consider using .replace('\n', something) to replace the 'newline' characters or string.split('\n') to split the entire document into a list of lines?

If you don't care about the lines and just want to retain the raw text, just replace them with whitespace characters by using .replace('\n', ' ').

jazzooi21
  • 13
  • 1
  • 6