To read the entire file as a string rather than a list?

Asked 2 years ago, Updated 2 years ago, 90 views

My file is

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

It looks like it. If you use the source code below and read it, ['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE'] It is separated by spaces and saved as a list.

What I want is "LLKKKKKKKKKKMMMMMMNNNNNNNNNNNNNNNNNGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH I want to sing it in a string form, what should I do?

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

file python input split

2022-09-21 18:32

1 Answers

readlines() read one line at a time from a file and save each line in a list format. read() reads the entire file, so it is appropriate to write read() if you have any questions.

myfile = open("input.txt")

lines = myfile.read()
print lines

Results:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

As you can see, I read the opening letter, too "LLKKKKKKKMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN\nGGGHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEE" "LLKKKKKKKMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEE" If you want

lines = myfile.read().replace('\n', ' ') You must replace the line \n with the blank character '.


2022-09-21 18:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.