如何将文本文件读入字符串变量并去除换行符?

发布于 2024-12-19 11:59:56 字数 274 浏览 0 评论 0 原文

我有一个如下所示的文本文件:

ABC
DEF

如何将文件读入不带换行符的单行字符串,在本例中创建字符串 'ABCDEF'


要将文件读入行列表,但从每行中删除尾随换行符,请参阅如何读取没有换行符的文件?.

I have a text file that looks like:

ABC
DEF

How can I read the file into a single-line string without newlines, in this case creating a string 'ABCDEF'?


For reading the file into a list of lines, but removing the trailing newline character from each line, see How to read a file without newlines?.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

冧九 2024-12-26 11:59:56

您可以使用:

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

或者如果文件内容保证为一行:

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

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()
银河中√捞星星 2024-12-26 11:59:56

在 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', '')
却一份温柔 2024-12-26 11:59:56

您可以在一行中读取文件:

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

请注意,这不会显式关闭文件。

CPython 将在文件作为垃圾收集的一部分退出时关闭该文件。

但其他 Python 实现则不会。要编写可移植代码,最好使用 with 或显式关闭文件。短并不总是更好。请参阅显式关闭文件重要吗?

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 Is explicitly closing files important?

濫情▎り 2024-12-26 11:59:56

要将所有行连接到字符串中并删除新行,我通常使用:

with open('t.txt') as f:
  s = " ".join([l.rstrip("\n") for l in f]) 

To join all lines into a string and remove new lines, I normally use:

with open('t.txt') as f:
  s = " ".join([l.rstrip("\n") for l in f]) 
俯瞰星空 2024-12-26 11:59:56

使用:

with open("data.txt") as myfile:
    data = "".join(line.rstrip() for line in myfile)

join() 将连接字符串列表,和 rstrip() 不带任何参数将修剪空白,包括换行符,从字符串末尾开始。

Use:

with open("data.txt") as myfile:
    data = "".join(line.rstrip() for line in myfile)

join() will join a list of strings, and rstrip() without any arguments will trim whitespace, including newlines, from the end of strings.

待"谢繁草 2024-12-26 11:59:56

还有splitlines()

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

变量data 现在是一个打印时看起来像这样的列表:

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

请注意,没有任何换行符 (\n)。

此时,听起来您想将这些行打印回控制台,这可以通过 for 循环来实现:

for line in data:
    print(line)

There is also splitlines():

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 aren't any 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)
清风疏影 2024-12-26 11:59:56

这可以使用 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()
回心转意 2024-12-26 11:59:56

很难确切地说出你在追求什么,但这样的事情应该可以帮助你开始:

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()])
往事随风而去 2024-12-26 11:59:56

我对此已经摆弄了一段时间,并且更喜欢将 readrstrip 结合使用。如果没有 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)
北方的韩爷 2024-12-26 11:59:56

这里有四个代码供您选择一个:

with open("my_text_file.txt", "r") as file:
    data = file.read().replace("\n", "")

with open("my_text_file.txt", "r") as file:
    data = "".join(file.read().split("\n"))

with open("my_text_file.txt", "r") as file:
    data = "".join(file.read().splitlines())

with open("my_text_file.txt", "r") as file:
    data = "".join([line for line in file])

Here are four codes for you to choose one:

with open("my_text_file.txt", "r") as file:
    data = file.read().replace("\n", "")

or

with open("my_text_file.txt", "r") as file:
    data = "".join(file.read().split("\n"))

or

with open("my_text_file.txt", "r") as file:
    data = "".join(file.read().splitlines())

or

with open("my_text_file.txt", "r") as file:
    data = "".join([line for line in file])
百思不得你姐 2024-12-26 11:59:56
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)
肥爪爪 2024-12-26 11:59:56

您还可以剥离每一行并连接成最终的字符串。

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.

毁梦 2024-12-26 11:59:56

您可以将其压缩为两行代码!

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
吾家有女初长成 2024-12-26 11:59:56

Python 3:请参阅方括号语法的列表推导式

 with open('data.txt') as f:
     lines = [ line.rstrip('\n') for line in f ]

Python 3: See List Comprehensions for the square bracket syntax.

 with open('data.txt') as f:
     lines = [ line.rstrip('\n') for line in f ]
冬天的雪花 2024-12-26 11:59:56

这是一个单行、可复制粘贴的解决方案,还可以关闭文件对象:

_ = 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()
爱她像谁 2024-12-26 11:59:56

Oneliner:

  • 列表:"".join([line.rstrip('\n') for line in open('file.txt')])

  • 生成器:"".join( (line.rstrip('\n') for line in open('file.txt')))

列表比生成器更快,但占用内存更大。生成器比列表慢,并且像迭代行一样更节省内存。对于“”.join(),我认为两者都应该工作得很好。应删除 .join() 函数以分别获取列表或生成器。

  • 注意: close() / 关闭文件描述符可能不需要

Oneliner:

  • List: "".join([line.rstrip('\n') for line in open('file.txt')])

  • Generator: "".join((line.rstrip('\n') for line in open('file.txt')))

List is faster than generator but heavier on memory. Generators are slower than lists and is lighter for memory like iterating over lines. In case of "".join(), I think both should work well. .join() function should be removed to get list or generator respectively.

  • Note: close() / closing of file descriptor probably not needed
走过海棠暮 2024-12-26 11:59:56

用途:

from pathlib import Path
line_lst = Path("to/the/file.txt").read_text().splitlines()

这是获取文件所有行的最佳方法。 '\n' 已经被 splitlines() 剥离(它可以智能地识别 win/mac/unix 行类型)。

但如果您仍然想删除每一行:

line_lst = [line.strip() for line in txt = Path("to/the/file.txt").read_text().splitlines()]

strip() 只是一个有用的示例,但您可以根据需要处理您的行。

最后,您只想要串联文本吗?

txt = ''.join(Path("to/the/file.txt").read_text().splitlines())

Use:

from pathlib import Path
line_lst = Path("to/the/file.txt").read_text().splitlines()

It is the best way to get all the lines of a file. The '\n' are already stripped by the splitlines() (which smartly recognize win/mac/unix lines types).

But if nonetheless you want to strip each lines:

line_lst = [line.strip() for line in txt = Path("to/the/file.txt").read_text().splitlines()]

strip() was just a useful exemple, but you can process your line as you please.

At the end, do you just want concatenated text?

txt = ''.join(Path("to/the/file.txt").read_text().splitlines())
后eg是否自 2024-12-26 11:59:56

试试这个:

x = "yourfilename.txt"
y = open(x, 'r').read()

print(y)

Try this:

x = "yourfilename.txt"
y = open(x, 'r').read()

print(y)
一个人的旅程 2024-12-26 11:59:56

要使用 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

enter image description here

热情消退 2024-12-26 11:59:56

我认为没有人解决了您问题的 [ ] 部分。当您将每一行读入变量时,因为在将 \n 替换为 '' 之前有多行,所以您最终创建了一个列表。如果您有一个变量 x 并仅通过

x

或 print(x)

或 str(x)

将其打印出来,您将看到带有括号的整个列表。如果您调用(排序数组)

x[0] 的每个元素
然后它省略了括号。如果您使用 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])

☆獨立☆ 2024-12-26 11:59:56

正则表达式也可以工作:

import re
with open("depression.txt") as f:
     l = re.split(' ', re.sub('\n',' ', f.read()))[:-1]

print (l)

输出:

[‘我’、‘感觉’、‘空’、‘和’、‘死’、‘里面’]

A regular expression works too:

import re
with open("depression.txt") as f:
     l = re.split(' ', re.sub('\n',' ', f.read()))[:-1]

print (l)

Output:

['I', 'feel', 'empty', 'and', 'dead', 'inside']

明明#如月 2024-12-26 11:59:56

你可以试试这个。我在我的程序中使用它。

Data = open('data.txt', 'r')
data = Data.readlines()
for i in range(len(data)):
    data[i] = data[i].strip() + ' '
data = ''.join(data).strip()

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()
玻璃人 2024-12-26 11:59:56

这有效:
将文件更改为:

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
千纸鹤 2024-12-26 11:59:56
with open('data.txt', 'r') as file:
    data = [line.strip('\n') for line in file.readlines()]
    data = ''.join(data)
with open('data.txt', 'r') as file:
    data = [line.strip('\n') for line in file.readlines()]
    data = ''.join(data)
昔梦 2024-12-26 11:59:56
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
唐婉 2024-12-26 11:59:56

用途:

with open(player_name, 'r') as myfile:
    data = myfile.readline()
    list = data.split(" ")
    word = list[0]

此代码将帮助您读取第一行,然后使用列表和拆分选项,您可以将由空格分隔的第一行单词转换为存储在列表中。

那么您可以轻松访问任何单词,甚至将其存储在字符串中。

您还可以使用 for 循环执行相同的操作。

Use:

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.

then 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.

好多鱼好多余 2024-12-26 11:59:56

请尝试以下操作:

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 weren’t any \n.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文