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

ABC
DEF

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


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


当前回答

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

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

其他回答

在Python 3.5或更高版本中,使用pathlib可以将文本文件内容复制到一个变量中,并在一行中关闭文件:

from pathlib import Path
txt = Path('data.txt').read_text()

然后你可以使用str.replace删除换行符:

txt = txt.replace('\n', '')
f = open('data.txt','r')
string = ""
while 1:
    line = f.readline()
    if not line:break
    string += line

f.close()


print(string)

如此: 将文件更改为:

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

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

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

你可以用:

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

或者文件内容保证为一行

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