Reputation: 2324
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)
Upvotes: 0
Views: 2598
Reputation: 2257
f = open("file", "r")
print "".join(f.read().split()) # Strips all white-spaces
Upvotes: 0
Reputation: 8726
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.
Upvotes: 0
Reputation: 1121386
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.
Upvotes: 1
Reputation:
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", "")
Upvotes: 0
Reputation: 4801
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.
Upvotes: 0