I'm trying to use Python to open a .txt file and remove a single white space if it exists from the end of each line, BUT all the new lines and formatting has to remain. I need to check each individual line in the .txt file and if there are any lines with a single space at the end, I need to remove just that single space for those lines, that's it. Everything else must remain intact. Is this possible?
Asked
Active
Viewed 2,347 times
1
-
Yes, it is possible. What code do you have so far? What problems did you encounter? – fjarri Mar 18 '15 at 00:37
-
What if there are more than one spaces? – thefourtheye Mar 18 '15 at 00:37
-
@thefourtheye That will never occur. There will either just be one space, or none. – Vimzy Mar 18 '15 at 00:37
-
@fjarri I have an entire program that outputs to a .txt file, but these white spaces are the only issue I'm having when I output my new .txt file. – Vimzy Mar 18 '15 at 00:38
-
What is the actual problem? Do you know how to split your file contents into lines? Do you know how to check if a line ends with a space? Do you know how to remove the last character from a line? Do you know how to join the lines back into a single string? If you know all that, you know how to solve your problem. – fjarri Mar 18 '15 at 00:41
-
See [this similar question](http://stackoverflow.com/questions/29111443/remove-space-at-end-of-string-but-keep-new-line-symbol/29111556). – TigerhawkT3 Mar 18 '15 at 00:43
-
@TigerhawkT3 No this is a difference scenario. – Vimzy Mar 18 '15 at 00:50
-
Why not avoid outputting the spaces in the first place? `' '.join()` is often helpful. Can you show how you are writing the file? or a similar example? – John La Rooy Mar 18 '15 at 00:51
1 Answers
0
Why not something like:
for line in input_file:
if line.endswith(" \n"):
line = line.replace(' \n', '\n')
Followed by whatever steps you take to collect the reviewed/modified inputs for later outputting.
There may be a cleverer way to do it, but this should work.
Editted to reflect a more readable fix.

selllikesybok
- 1,250
- 11
- 17
-
2Maybe `line = line.replace(' \n', '\n')`? If it's coming from a text file, there shouldn't be more than one `'\n'` per line. – TigerhawkT3 Mar 18 '15 at 01:19
-
@TigerhawkT3 - good point. Not sure it will matter for performance, but it does improve readability. – selllikesybok Mar 18 '15 at 01:22