Skip to content

Instantly share code, notes, and snippets.

@tomviner
Created September 23, 2016 09:24
Show Gist options
  • Save tomviner/2bd9518c902307c93bfce737bb5a64fa to your computer and use it in GitHub Desktop.
Save tomviner/2bd9518c902307c93bfce737bb5a64fa to your computer and use it in GitHub Desktop.
Random access file writing
import os
import time
import random
FN = 'my-tmp-file.txt'
SIZE = (2 ** 10) # 1K
if not os.path.exists(FN):
with open(FN, 'wb') as f:
# f.truncate(SIZE - 1)
# # f.write('start')
f.seek(SIZE - 1)
f.write('\0')
print open(FN, 'rb').read()
while True:
index = random.randint(0, SIZE)
print index
with open(FN, 'r+b') as f:
f.seek(index)
f.write('-{}-'.format(index))
print open(FN, 'rb').read(SIZE - 1)
time.sleep(0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment