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