0

Create a text file with name filename and about size bytes. The file should contain an incrementing number on each line starting with 0. (ie) 0, 1, 2, 3, .... as many are required to make the file size just >= size. Each line should end with windows newline ("\r\n").

create_file_numbers(filename, size)

should give a file as explained above

i tried using:

  while os.path.getsize(filename) < size:
     f.write(str(i)+"\r\n")
     i += 1

But not getting the required result!

  • This link might be a hint: http://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python – Mehdi Jan 19 '14 at 12:41
  • Possibly `os.path.getsize()` will only tell you the size of the file as written to disk - part of it might not be flushed from IO buffers yet. Either explicitly flush `f`, or just keep track of how many bytes you wrote instead of using `getsize()` – millimoose Jan 19 '14 at 12:59

1 Answers1

0

Since it's just digits and '\r\n' and no unicode character involved, you can just count characters in final string with len(str). I assumed 1 character = 1 byte.

def create_file_numbers(filename, size):
    f = open(filename, 'w')

    text = ''
    i = 0
    line = str(i)
    while len(text + line) <= size:
        text += line
        i += 1
        line = '\r\n' + str(i)

    f.write(text)
    f.close()
Mehdi
  • 4,202
  • 5
  • 20
  • 36