How to remove spaces from file to make one long line?

Viewed 130

I want to read a file and remove the spaces. I swear I've done this multiple times, but some reason the method I used to use doesn;t seem to be working. I must be making some small mistake somewhere, so I decided to make a small practice file (because the files I actually need to use are EXTREMELY LARGE) to find out.

the original file says:

abcdefg (new line) hijklmn

but I want it to say: abcdefghijklmn

file = open('please work.txt', 'r')
for line in file:
  lines = line.strip()
  print(lines)
close.file()

However, it just says: abcdefg (new line) hijklmn

and when I use line.strip('\n') it says: abcdefg (big new line) hijklmn

Any help will be greatly appreciated, because this was the first thing I learned and suddenly I can't remember how to use it!

3 Answers

If what you want to do is to concatenate each line into a single line, you could utilize rstrip and concatenate to a result variable:

with open('test.txt', 'r') as fin:
    lines = ''
    for line in fin:
        stripped_line = line.rstrip()
        lines += stripped_line
    print(lines)

From a text file looking like this:

abcdefg hijklmnop
this is a line   

The result would be abcdefg hijklmnopthis is a line. If you did want to remove the whitespace as well you could lines = lines.replace(' ','') after the loop which would result in abcdefghijklmnopthisisaline.

The (new line) in your output is from the print, which will output a \n. you can use print(lines, end='') to remove it.

strip() only removes leading & trailing spaces.

You can use string.replace(' ', '') to remove all spaces.

'abcdefg (new line) hijklmn'.replace(' ', '')

If your file has tab newline or other forms of spaces, the above will not work and you will need to use regex to remove all forms of space in the file.

import re
string = '''this is a \n
test \t\t\t
\r
\v

'''

re.sub(r'\s', '', string)
#'thisisatest'
Related