问题:如何将文本文件读入字符串变量并删除换行符?
我使用以下代码段在python中读取文件:
with open ("data.txt", "r") as myfile:
data=myfile.readlines()
输入文件为:
LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE
当我打印数据时
['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']
如我所见,数据是list
形式形式的。我如何使其成为字符串?而且我怎么删除"\n"
,"["
以及"]"
从中字符?
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?
回答 0
您可以使用:
with open('data.txt', 'r') as file:
data = file.read().replace('\n', '')
You could use:
with open('data.txt', 'r') as file:
data = file.read().replace('\n', '')
回答 1
使用read()
,而不是readline()
:
with open('data.txt', 'r') as myfile:
data = myfile.read()
Use read()
, not readline()
:
with open('data.txt', 'r') as myfile:
data = myfile.read()
回答 2
You can read from a file in one line:
str = open('very_Important.txt', 'r').read()
Please note that this does not close the file explicitly.
CPython will close the file when it exits as part of the garbage collection.
But other python implementations won’t. To write portable code, it is better to use with
or close the file explicitly. Short is not always better. See https://stackoverflow.com/a/7396043/362951
回答 3
要将所有行连接到字符串中并删除新行,我通常使用:
with open('t.txt') as f:
s = " ".join([x.strip() for x in f])
To join all lines into a string and remove new lines I normally use :
with open('t.txt') as f:
s = " ".join([x.strip() for x in f])
回答 4
在Python 3.5或更高版本中,可以使用pathlib将文本文件的内容复制到一个变量中并在一行中关闭该文件:
from pathlib import Path
txt = Path('data.txt').read_text()
然后您可以使用str.replace删除换行符:
txt = txt.replace('\n', '')
In Python 3.5 or later, using pathlib you can copy text file contents into a variable and close the file in one line:
from pathlib import Path
txt = Path('data.txt').read_text()
and then you can use str.replace to remove the newlines:
txt = txt.replace('\n', '')
回答 5
with open("data.txt") as myfile:
data="".join(line.rstrip() for line in myfile)
join()将加入一个字符串列表,而不带参数的rstrip()将从字符串末尾修剪空白,包括换行符。
with open("data.txt") as myfile:
data="".join(line.rstrip() for line in myfile)
join() will join a list of strings, and rstrip() with no arguments will trim whitespace, including newlines, from the end of strings.
回答 6
这可以使用read()方法完成:
text_as_string = open('Your_Text_File.txt', 'r').read()
或者由于默认模式本身是“ r”(读取),因此只需使用,
text_as_string = open('Your_Text_File.txt').read()
This can be done using the read() method :
text_as_string = open('Your_Text_File.txt', 'r').read()
Or as the default mode itself is ‘r’ (read) so simply use,
text_as_string = open('Your_Text_File.txt').read()
回答 7
我已经摆弄了一段时间,并且更喜欢与read
结合使用rstrip
。如果不使用rstrip("\n")
,Python会在字符串末尾添加换行符,这在大多数情况下不是很有用。
with open("myfile.txt") as f:
file_content = f.read().rstrip("\n")
print file_content
I have fiddled around with this for a while and have prefer to use use read
in combination with rstrip
. Without rstrip("\n")
, Python adds a newline to the end of the string, which in most cases is not very useful.
with open("myfile.txt") as f:
file_content = f.read().rstrip("\n")
print file_content
回答 8
很难确切地知道您要做什么,但是这样的事情应该可以帮助您入门:
with open ("data.txt", "r") as myfile:
data = ' '.join([line.replace('\n', '') for line in myfile.readlines()])
It’s hard to tell exactly what you’re after, but something like this should get you started:
with open ("data.txt", "r") as myfile:
data = ' '.join([line.replace('\n', '') for line in myfile.readlines()])
回答 9
我很惊讶没有人提及splitlines()
。
with open ("data.txt", "r") as myfile:
data = myfile.read().splitlines()
data
现在,变量是一个列表,在打印时如下所示:
['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']
请注意,没有换行符(\n
)。
那时,这听起来像是要将行打印回控制台,您可以使用for循环来实现:
for line in data:
print line
I’m surprised nobody mentioned splitlines()
yet.
with open ("data.txt", "r") as myfile:
data = myfile.read().splitlines()
Variable data
is now a list that looks like this when printed:
['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']
Note there are no newlines (\n
).
At that point, it sounds like you want to print back the lines to console, which you can achieve with a for loop:
for line in data:
print line
回答 10
您还可以删除每行并连接成最终字符串。
myfile = open("data.txt","r")
data = ""
lines = myfile.readlines()
for line in lines:
data = data + line.strip();
这也可以解决。
You can also strip each line and concatenate into a final string.
myfile = open("data.txt","r")
data = ""
lines = myfile.readlines()
for line in lines:
data = data + line.strip();
This would also work out just fine.
回答 11
您可以将其压缩为两行代码!!!!
content = open('filepath','r').read().replace('\n',' ')
print(content)
如果您的文件显示为:
hello how are you?
who are you?
blank blank
python输出
hello how are you? who are you? blank blank
you can compress this into one into two lines of code!!!
content = open('filepath','r').read().replace('\n',' ')
print(content)
if your file reads:
hello how are you?
who are you?
blank blank
python output
hello how are you? who are you? blank blank
回答 12
这是一个可复制粘贴的单行解决方案,它也关闭了文件对象:
_ = open('data.txt', 'r'); data = _.read(); _.close()
This is a one line, copy-pasteable solution that also closes the file object:
_ = open('data.txt', 'r'); data = _.read(); _.close()
回答 13
f = open('data.txt','r')
string = ""
while 1:
line = f.readline()
if not line:break
string += line
f.close()
print string
f = open('data.txt','r')
string = ""
while 1:
line = f.readline()
if not line:break
string += line
f.close()
print string
回答 14
python3:如果您对方括号语法不陌生,请使用Google“列表注释”。
with open('data.txt') as f:
lines = [ line.strip( ) for line in list(f) ]
python3: Google “list comphrension” if the square bracket syntax is new to you.
with open('data.txt') as f:
lines = [ line.strip( ) for line in list(f) ]
回答 15
你有试过吗?
x = "yourfilename.txt"
y = open(x, 'r').read()
print(y)
Have you tried this?
x = "yourfilename.txt"
y = open(x, 'r').read()
print(y)
回答 16
我认为没有人解决您问题的[]部分。当您将每一行读入变量时,由于在用\替换\ n之前有多行,所以最终创建了一个列表。如果您有一个x变量,并通过以下方式将其打印出来
X
或打印(x)
或str(x)
您将看到带有括号的整个列表。如果您调用(排序数组)的每个元素
x [0]则省略括号。如果您使用str()函数,您将只会看到数据,而不会看到“”。str(x [0])
I don’t feel that anyone addressed the [ ] part of your question. When you read each line into your variable, because there were multiple lines before you replaced the \n with ” you ended up creating a list. If you have a variable of x and print it out just by
x
or print(x)
or str(x)
You will see the entire list with the brackets. If you call each element of the (array of sorts)
x[0] then it omits the brackets. If you use the str() function you will see just the data and not the ” either. str(x[0])
回答 17
也许您可以尝试一下?我在程序中使用它。
Data= open ('data.txt', 'r')
data = Data.readlines()
for i in range(len(data)):
data[i] = data[i].strip()+ ' '
data = ''.join(data).strip()
Maybe you could try this? I use this in my programs.
Data= open ('data.txt', 'r')
data = Data.readlines()
for i in range(len(data)):
data[i] = data[i].strip()+ ' '
data = ''.join(data).strip()
回答 18
正则表达式也适用:
import re
with open("depression.txt") as f:
l = re.split(' ', re.sub('\n',' ', f.read()))[:-1]
print (l)
[‘I’,’feel’,’empty’,’and’,’dead’,’inside’]
Regular expression works too:
import re
with open("depression.txt") as f:
l = re.split(' ', re.sub('\n',' ', f.read()))[:-1]
print (l)
[‘I’, ‘feel’, ’empty’, ‘and’, ‘dead’, ‘inside’]
回答 19
要使用Python删除换行符,您可以使用replace
字符串函数。
本示例删除所有3种换行符:
my_string = open('lala.json').read()
print(my_string)
my_string = my_string.replace("\r","").replace("\n","")
print(my_string)
示例文件为:
{
"lala": "lulu",
"foo": "bar"
}
您可以使用以下重播方案进行尝试:
https://repl.it/repls/AnnualJointHardware
To remove line breaks using Python you can use replace
function of a string.
This example removes all 3 types of line breaks:
my_string = open('lala.json').read()
print(my_string)
my_string = my_string.replace("\r","").replace("\n","")
print(my_string)
Example file is:
{
"lala": "lulu",
"foo": "bar"
}
You can try it using this replay scenario:
https://repl.it/repls/AnnualJointHardware
回答 20
这有效:将文件更改为:
LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE
然后:
file = open("file.txt")
line = file.read()
words = line.split()
这将创建一个列表words
,该列表等于:
['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']
那摆脱了“ \ n”。要回答括号中的问题,只需执行以下操作:
for word in words: # Assuming words is the list above
print word # Prints each word in file on a different line
要么:
print words[0] + ",", words[1] # Note that the "+" symbol indicates no spaces
#The comma not in parentheses indicates a space
返回:
LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN, GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE
This works: Change your file to:
LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE
Then:
file = open("file.txt")
line = file.read()
words = line.split()
This creates a list named words
that equals:
['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']
That got rid of the “\n”. To answer the part about the brackets getting in your way, just do this:
for word in words: # Assuming words is the list above
print word # Prints each word in file on a different line
Or:
print words[0] + ",", words[1] # Note that the "+" symbol indicates no spaces
#The comma not in parentheses indicates a space
This returns:
LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN, GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE
回答 21
with open(player_name, 'r') as myfile:
data=myfile.readline()
list=data.split(" ")
word=list[0]
此代码将帮助您阅读第一行,然后使用list and split选项可以转换以空格分隔的第一行单词以存储在列表中。
比起您可以轻松访问任何单词,甚至将其存储在字符串中而言。
您也可以使用for循环执行相同的操作。
with open(player_name, 'r') as myfile:
data=myfile.readline()
list=data.split(" ")
word=list[0]
This code will help you to read the first line and then using the list and split option you can convert the first line word separated by space to be stored in a list.
Than you can easily access any word, or even store it in a string.
You can also do the same thing with using a for loop.
回答 22
file = open("myfile.txt", "r")
lines = file.readlines()
str = '' #string declaration
for i in range(len(lines)):
str += lines[i].rstrip('\n') + ' '
print str
file = open("myfile.txt", "r")
lines = file.readlines()
str = '' #string declaration
for i in range(len(lines)):
str += lines[i].rstrip('\n') + ' '
print str
回答 23
尝试以下方法:
with open('data.txt', 'r') as myfile:
data = myfile.read()
sentences = data.split('\\n')
for sentence in sentences:
print(sentence)
注意:它不会删除\n
。仅用于查看文本,好像没有\n
Try the following:
with open('data.txt', 'r') as myfile:
data = myfile.read()
sentences = data.split('\\n')
for sentence in sentences:
print(sentence)
Caution: It does not remove the \n
. It is just for viewing the text as if there were no \n
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。