0

Like I said in the title, my script only seems to work on the first line.
Here is my script:

#!/usr/bin/python

import sys



def main():
  a = sys.argv[1]
  f = open(a,'r')
  lines = f.readlines()
  w = 0
  for line in lines:
    spot = 0
    cp = line
    for char in reversed(cp):
      x = -1
      if char == ' ':
        del line[x]
        w += 0
      if char != '\n' or char != ' ':
        lines[spot] = line
        spot += 1
        break
      x += 1
  f.close()
  f = open(a,'w')
  f.writelines(lines)
  print("White Space deleted: "+str(w))


if __name__ == "__main__":
  main()

I'm not too experienced when it comes to loops.

6
  • 2
    string.rstrip() will trim white space off the end of a string.
    – kylieCatt
    Feb 17, 2014 at 16:49
  • 2
    You do know Python has a str.rstrip() method, right? It removes whitespace from the end of lines..
    – Martijn Pieters
    Feb 17, 2014 at 16:49
  • w += 0 is probably not what you wanted..
    – Martijn Pieters
    Feb 17, 2014 at 16:49
  • Oh yeah, but that just counts how many spaces have been deleted @MartijnPieters
    – Awalrod
    Feb 17, 2014 at 16:51
  • @Awalrod: So you count to 0 every time.
    – Martijn Pieters
    Feb 17, 2014 at 16:53

3 Answers 3

3

The following script do the same thing as your program, more compactly:

import fileinput

deleted = 0
for line in fileinput.input(inplace=True):
    stripped = line.rstrip()
    deleted += len(line) - len(stripped) + 1  # don't count the newline
    print(stripped)

print("Whitespace deleted: {}".format(deleted))

Here str.rstrip() removes all whitespace from the end of a line (newlines, spaces and tabs).

The fileinput module takes care of handling sys.argv for you, opening files one by one if you name more than one file.

Using print() will add the newline back on to the end of the stripped lines.

3
  • If somebody else is wondering: "Optional in-place filtering: if the keyword argument inplace=1 is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place." Feb 17, 2014 at 16:55
  • This works, but why doesn't print(line.rstrip()) output to the terminal? Also, what does the inplace=True mean.
    – Awalrod
    Feb 17, 2014 at 17:01
  • @Awalrod: the fileinput.input(inplace=True) call redirects sys.stdout to the output file. Printing then writes to the replacement file instead. This is a feature of that module. inplace=True enables that feature.
    – Martijn Pieters
    Feb 17, 2014 at 17:04
0

Just use rstrip:

f = open(a,'r')
lines = f.readlines()
f.close()
f = open(a,'w')
for line in lines:
    f.write(line.rstrip()+'\n')
f.close()
0

rstrip() is probably what you want to use to achieve this.

>>> 'Here is my string       '.rstrip()
'Here is my string'

A more compact way to iterate backwards over stings is

>>> for c in 'Thing'[::-1]:
        print(c)


g
n
i
h
T

[::-1] is slice notation. SLice notaion can be represented as [start:stop:step]. In my example a -1 for the step means it will step form the back by one index. [x:y:z] will start at index x stop at y-1 and go forward by z places each step.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.