0

I am using something like:

tmp=fileA.read(4)
outfile.write(tmp)

But there comes the problem if fileA is reaching the end and only 2 bytes is left. In that case, the content of tmp will be

xx (Not XXXX any more)

And I would like to compensate the missing x by 0, so it can be like

xx00

When I write into the file outfile

THe question is, I know I can use function

len(tmp)

to know how many 0 I need to add, is there any easy way to do this adding operation?

I can think of

if len(tmp) == 2 : tmp = tmp + "00"
elif len(tmp) == 3: .......

But this is some kind of "stupid" method.

Is there a way to do it like:

tmp << (4-len(tmp)) | "0000"

Thanks for your help

thundium
  • 873
  • 1
  • 12
  • 28
  • Can you describe the *actual problem* you are trying to solve? – Burhan Khalid Aug 22 '13 at 12:58
  • possible duplicate of [fill out a python string with spaces?](http://stackoverflow.com/questions/5676646/fill-out-a-python-string-with-spaces) – Oli Aug 22 '13 at 13:10

2 Answers2

9

Str has a function for what you are trying to do:

tmp=fileA.read(4)
tmp.ljust(4, '0')
outfile.write(tmp)

Ex:

'aa'.ljust(4, '0') => 'aa00'
Samy Arous
  • 6,515
  • 11
  • 19
2

check out simple program where '1.txt' contains some bytes data and we are reading 4 byte each.

fp1 = open("1.txt", "r") 
fp2 = open("2.txt", "w")

while True:
    line = fp1.read(4).strip()  if not line: # end of file checking          break
    # filling remaining byte with zero having len < 4
    data = line.zfill(4)[::-1]
    print "Writting to file2 :: ", data
    fp2.write(line)
fp1.close() 
fp2.close()
Mahesh Shitole
  • 737
  • 6
  • 14
  • Doesn't that reverse numbers? Like if fp1.read(4) is 32, the result would be 2300 ? – Jblasco Aug 22 '13 at 13:39
  • You should alway use the with statement when opening a file or otherwise use a try, except, finally block in order to safely close the file stream. – Samy Arous Aug 22 '13 at 14:06