我需要帮助如何将一个txt文件中的多行连接成一行,而不需要空格
文本文件由8行组成,每行有80个字符,如下所示:
(来源: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])
(来源:gulfup.com)
甚至更好
^{pr2}$只需将文件的行读入列表并使用
''.join()
:.strip()
调用从行的开始和结尾删除所有空白,在本例中是换行符。在在
print
语句中使用逗号不仅可以省略换行符,还可以在参数之间打印一个空格。在如果文件不是特别大,可以将整个内容作为一个字符串打开。在
content = inFile.read()
文本行由特殊字符
\n
分割。如果你想把所有的东西都放在一行上,去掉那个字符。在
oneLine = content.replace('\n', '')
这里,我用一个空字符串替换每个
\n
字符。在相关问题 更多 >
编程相关推荐