[SOLVED] How to read a text file into a string variable and strip newlines?

Issue

I use the following code segment to read a file in python:

with open ("data.txt", "r") as myfile:
    data=myfile.readlines()

Input file is:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

and when I print data I get

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

As I see data is in list form. How do I make it string? And also how do I remove the "\n", "[", and "]" characters from it?

Solution

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

Answered By – sleeplessnerd

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

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