如何将文本文件中的行(字符)输出到单个lin中

2024-10-04 09:29:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助如何将一个txt文件中的多行连接成一行,而不需要空格

文本文件由8行组成,每行有80个字符,如下所示:

a busy cat
(来源:gulfup.com

下面是我使用的代码,但我的问题是,我无法将所有的行连接起来,它们之间没有空格:

inFile = open ("text.txt","r") # open the text file
line1 = inFile.readline() # read the first line from the text.txt file
line2 = inFile.readline() # read the second line from the text.txt file
line3 = inFile.readline()
line4 = inFile.readline()
line5 = inFile.readline()
line6 = inFile.readline()
line7 = inFile.readline()
line8 = inFile.readline()

print (line1.split("\n")[0], # split each line and print it --- My proplem in this code!
       line2.split("\n")[0],
       line3.split("\n")[0],
       line4.split("\n")[0],
       line5.split("\n")[0],
       line6.split("\n")[0],
       line7.split("\n")[0],
       line8.split("\n")[0])

a busy cat
(来源:gulfup.com


Tags: thetexttxtcomreadreadlineline来源
3条回答
infile = open("text.txt", "r")
lines = infile.readlines()
merged = ''.join(lines).replace("́\n", "")

甚至更好

^{pr2}$

只需将文件的行读入列表并使用''.join()

with open ("text.txt","r") as inFile:
    lines = [l.strip() for l in inFile]
    print ''.join(lines)

.strip()调用从行的开始和结尾删除所有空白,在本例中是换行符。在

print语句中使用逗号不仅可以省略换行符,还可以在参数之间打印一个空格。在

如果文件不是特别大,可以将整个内容作为一个字符串打开。在

content = inFile.read()

文本行由特殊字符\n分割。
如果你想把所有的东西都放在一行上,去掉那个字符。在

oneLine = content.replace('\n', '')

这里,我用一个空字符串替换每个\n字符。在

相关问题 更多 >