1,105,578 Community Members

Removing Trailing Spaces

Member Avatar
polanski
Newbie Poster
2 posts since Dec 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

Hey everyone, new here.

I'm looking for a little help with my program. Its supposed to take a txt file called test.txt, and removes all spaces trailing at the end of lines.

ex. (note the spaces)
"python " -> "python"
"daniweb is great" -> "daniweb is great"
" forum" -> " forum"

The code below has gone through many rewrites, but it still doesn't work. At first it would delete a good chunk of the txt in the file seemingly randomly, but now it deletes all the text from the file.

txt = open(test.txt,"r")
loriginal = f.readline()
txt = open(test.txt,"w")
l = line.split()
for i in range(len(l)):
    if l[i] == "/n":
        del line[i:]
txt.close()

Needless to say, this piece of code doesn't work. Can anyone shed some light on this and help me out?

Thanks in advance.

Cheers,

Member Avatar
Gribouillis
Posting Maven
3,456 posts since Jul 2008
Reputation Points: 1,140 [?]
Q&As Helped to Solve: 884 [?]
Skill Endorsements: 18 [?]
Moderator
 
1
 

You can use a regular expression

import re
sp_regex = re.compile(r"[ \t]+$", re.MULTILINE)
filename = "test.txt"
with open(filename) as f_in:
    content = f_in.read()
with open(filename, "w") as f_out:
    f_out.write(sp_regex.sub('', content))
Member Avatar
pyTony
pyMod
6,104 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 

test.txt is not good variable name you should probably have 'test.txt', loriginal will contain fist line of file, line is not defined, split is splitting (you should use rstrip), newline is by the way '\n'... Your code is junk. Start over, if you need to cheat, check my answer in the other thread.

Member Avatar
richieking
Posting Shark
926 posts since Jun 2009
Reputation Points: 40 [?]
Q&As Helped to Solve: 172 [?]
Skill Endorsements: 3 [?]
 
0
 

Do you want to strip all spaces ???
This will join all the text together.

New line is also counted as space so what are you realy looking for?
;)

Question Answered as of 3 Years Ago by richieking, pyTony and Gribouillis
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article