[英]How to output lines ( of characters) from a text file into a single line
I need help in how to connect multiple lines from a txt file into one single line without white spaces 我需要帮助,如何将txt文件中的多行连接成一行而不留空格
The text file is consisting of 8 lines and each single line has 80 characters, as showing: 文本文件由8行组成,每行包含80个字符,如下所示:
(source: gulfup.com ) (来源: gulfup.com )
Here is the code that I used, but my problem is that I am not able have all the lines connected with NO white spaces between them: 这是我使用的代码,但是我的问题是我无法使所有的线之间都没有空格连接:
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])
(source: gulfup.com ) (来源: gulfup.com )
Just read the lines of the file into a list and use ''.join()
: 只需将文件的各行读入一个列表并使用''.join()
:
with open ("text.txt","r") as inFile:
lines = [l.strip() for l in inFile]
print ''.join(lines)
The .strip()
call removes all whitespace from the start and end of the line, in this case the newline. .strip()
调用从行的开头和结尾删除所有空格,在本例中为换行符。
Using a comma with the print
statement does more than just omit the newline, it also prints a space between the arguments. 在print
语句中使用逗号不仅可以省略换行符,还可以在参数之间打印一个空格。
If your file isn't extraordinarily large, you can open the entire contents as one string. 如果文件不是很大,则可以将整个内容作为一个字符串打开。
content = inFile.read()
Lines of text are split by a special character, \\n
. 文本行由特殊字符\\n
分隔。
If you want everything on one line, remove that character. 如果您希望所有内容都在一行上,请删除该字符。
oneLine = content.replace('\\n', '')
Here, I'm replacing every \\n
character with an empty string. 在这里,我用空字符串替换每个\\n
字符。
infile = open("text.txt", "r")
lines = infile.readlines()
merged = ''.join(lines).replace("́\n", "")
or even better 甚至更好
infile = open("text.txt", "r")
lines = infile.read()
text = lines.replace("\n", "")
Try: 尝试:
lines = ''.join(open("text.txt").read().splitlines())
lines will be a string comprised of all the lines in the text.txt concatenated to each other without the '\\n' character. 行将是由text.txt中的所有行组成的字符串,这些行彼此连接,且不带'\\ n'字符。
f = open("file", "r")
print "".join(f.read().split()) # Strips all white-spaces
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.