Q:

Read text file into a variable and replace all newlines with space using python programming

0

Read text file into a variable and replace all newlines with space

Given: Assume you have a following text file (sample.txt).

Line1
line2
line3
line4
line5

Expected Output:

Line1 line2 line3 line4 line5

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

  • First, read a text file.
  • Next, use string replace() function to replace all newlines (\n) with space (' ').

Solution:

  • First, open the file in a read mode
  • Next, read all content from a file using the read() function and assign it to a variable.
  • Next, use string replace() function to replace all newlines (\n) with space (' ').
  • Display final string
with open('sample.txt', 'r') as file:
    data = file.read().replace('\n', ' ')
    print(data)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Remove items from a list while iterating using pyt... >>
<< Reverse each word of a string using python program...