Hey guys, this code is supposed to remove all the spaces at the end of each line. However from what I can tell it prints out the exact same file again instead of removing nothing. Have I been using the wrong test files? Or is there something wrong with my code?

f = open(filenm , "r")
line = f.readline()
for line in f:
    line = line.rstrip()
    print line

Thanks for the help guys

Your code seems fine, but I have a question, how do you realize whether or not the spaces are still there when you print it????

Your code seems fine, but I have a question, how do you realize whether or not the spaces are still there when you print it????

You're right. I made some quick changes to the code, but now it just seems to be removing random pieces of the file.

f = open(filenm , "r")
line = f.readline()
for line in f:
    line = line.rstrip()
    f = open(filenm, "w")
    f.write(line)
f.close()
with open(filenm) as infile:
     lines = tuple(line.rstrip() for line in infile)
with open(filenm,'w') as outfile:
     outfile.write('\n'.join(lines))
with open(filenm) as infile:
     lines = tuple(line.rstrip() for line in infile)
with open(filenm,'w') as outfile:
     outfile.write('\n'.join(lines))

Thank You for your help. But I'm not allowed to use "with." And I have not learnt tuple, or using a for loop like that. I'm going to go work on it with clues I got from your code.


Anyone else want to weigh in a help me out?

Cheers,

Polanski

rstrip()/strip() methods only strip well only on inputs. To make things simple.
if you recieve input from the user, then use the r/strip().


You can not use the strip only mechanism to strip a text file which is already formatted.

Also strip() methods will only strip the buffer provided. That means you can read word by word and strip them but what is the point as they will come striped already.

In short, only rstrip() will not get you what you want so tell your teacher ok?
;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.