Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

python - 如何将文本文件读入字符串变量并删除换行符?(How to read a text file into a string variable and strip newlines?)

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

(我使用以下代码段在python中读取文件:)

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

Input file is:

(输入文件为:)

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

and when I print data I get

(当我打印数据时)

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

As I see data is in list form.

(如我所见,数据是list形式的。)

How do I make it string?

(我如何使其成为字符串?)

And also how do I remove the "\n" , "[" , and "]" characters from it?

(还有如何从中删除"\n""[""]"字符?)

  ask by klijo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use:

(您可以使用:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...