delete the first whitespace from txt with python

Question:

I’ve trying delete the first whitespace of this txt but i don’t get it with this:

   with open(ruta, 'r', encoding="latin-1") as f:
       lines = f.readlines()
   lines = [line for line in lines if line.lstrip()]
   with open(ruta, 'w', encoding="latin-1") as f:
       f.writelines(lines)

Any suggestions what am I doing wrong?
Thx!

[1]: https://i.stack.imgur.com/MexaP.png [![example][1]][1]

Asked By: Su_80

||

Answers:

Replace your code with this:

with open(ruta, 'r', encoding="latin-1") as f:
       lines = f.readlines()
   lines = [line.lstrip() for line in lines]
   with open(ruta, 'w', encoding="latin-1") as f:
       f.writelines(lines)

There is no need for an if statement. You have to iterate through each element in ‘lines’ and then use the lstrip method to remove the white space. Then you have to add the element to ‘lines’ again.

Answered By: Dinux

With the following line the problem is that you are just filtering out lines whether they are truthy or not.

lines = [line for line in lines if line.lstrip()]

Move lstrip() to the beginning and that way it will remove the whitespaces as needed.

lines = [line.lstrip() for line in lines if line]

Update:
The if line part is not necessary if you don’t need to filter empty strings and other falsy values:

lines = [line.lstrip() for line in lines]
Answered By: CaptainCsaba
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.