-1

I am trying to read a fixed with file that has lines/records of different lengths. I need to stuff spaces at the end of the lines which are less than the standard length specified.

Any help appreciated.

enter image description here

Abhi
  • 163
  • 2
  • 14
  • Do you want to read, or to edit your file ? – Daneel Sep 23 '16 at 07:44
  • Please format your code properly. It's not runnable that way, since all indentation is missing. – MisterMiyagi Sep 23 '16 at 08:00
  • This also brings up the question: why do you need to pad lines with spaces in the first place? Are you trying to solve a different problem perhaps? – MisterMiyagi Sep 23 '16 at 08:02
  • I need to pad spaces as it is a fixed width file I am reading via python. The variables otherwise would throw error when assigned characters not read. – Abhi Sep 23 '16 at 08:04
  • Python has no concept for "fixed width file" unless you enforce it. You should try to fix the script actually processing the file, not fix the file. – MisterMiyagi Sep 23 '16 at 08:48

2 Answers2

2

You can use string.format to pad a string to a specific length.

The documentation says that < pads to the right so to pad a string with spaces to the right to a specific length you can do something like this:

>>> "{:<30}".format("foo")
'foo                           '
Raniz
  • 10,882
  • 1
  • 32
  • 64
  • This works with the test subject I had, will try to implement in the code and share results. Thanks heaps. – Abhi Sep 23 '16 at 08:05
1

You could consider to use ljust string method. If line is a line read from your file:

line = line.ljust(50)

will stuff the end of the line with spaces to get a 50 characters long line. If line is longer that 50, line is simply copied without any change.

Jal
  • 205
  • 1
  • 2
  • 8
  • The result set is having appended spaces in the beginning as well due to this, is that expected? – Abhi Sep 23 '16 at 08:26
  • 1
    You're probably putting spaces after the newline. Python may translate but not remove newline markers like `'\n'` when reading lines, so if you don't strip them before justifying you'll write the spaces on the line below. This is normally done with the rstrip method. You'll also need to add the newlines back before writing. – Yann Vernier Sep 23 '16 at 09:09