Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (1.6k points)

I used the below code 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? Also, how can I remove the characters, "\n", "[", and "]" from this output?

2 Answers

0 votes
by (25.1k points)

You could use:

with open('data.txt', 'r') as f:

    results = f.read().replace('\n', '')

0 votes
by (107k points)

You can read from a file in one line in Python:

str = open('very_Important.txt', 'r').read()

Please note that this does not close the file explicitly.

Related questions

0 votes
1 answer
asked Apr 7, 2021 in Linux by sheela_singh (9.5k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 11, 2020 in Python by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...