简体   繁体   中英

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

The text file is consisting of 8 lines and each single line has 80 characters, as showing:

忙碌的猫
(source: 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 )

Just read the lines of the file into a list and use ''.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.

Using a comma with the print statement does more than just omit the newline, it also prints a space between the arguments.

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 .
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.

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.

f = open("file", "r")
print "".join(f.read().split())    # Strips all white-spaces

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM