我有一个文本文件,看起来像:

ABC
DEF

我怎么能把文件读入一个单行字符串没有换行符,在这种情况下创建一个字符串'ABCDEF'?


有关将文件读入行列表,但从每行中删除末尾换行字符的操作,请参见如何读取不带换行符的文件?。


当前回答

你可以用:

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

或者文件内容保证为一行

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

其他回答

如此: 将文件更改为:

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

Or:

print words[0] + ",", words[1] # Note that the "+" symbol indicates no spaces
#The comma not in parentheses indicates a space

这将返回:

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

Join()将连接一个字符串列表,而不带参数的rstrip()将从字符串末尾删除空格,包括换行符。

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

我已经摆弄了一段时间,更喜欢将use read与rstrip结合使用。如果没有rstrip("\n"), Python会在字符串的末尾添加换行符,这在大多数情况下不是很有用。

with open("myfile.txt") as f:
    file_content = f.read().rstrip("\n")
    print(file_content)

如果您不熟悉方括号语法,则python3:谷歌“列表理解”。

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