>>> with open('New Text Document.txt') as my_file:
... # I already have file open at this point.. now what?
... my_file.seek(0) # Ensure you're at the start of the file..
... first_char = my_file.read(1) # Get the first character
... if not first_char:
... print "file is empty" # The first character is the empty string..
... else:
... my_file.seek(0) # The first character wasn't empty. Return to the start of the file.
... # Use file now
...
file is empty
>>> import os
>>> with open('new_file.txt') as my_file:
... my_file.seek(0, os.SEEK_END) # go to end of file
... if my_file.tell(): # if current position is truish (i.e != 0)
... my_file.seek(0) # rewind the file for later use
... else:
... print "file is empty"
...
file is empty
import json
import os
def append_json_to_file(filename, new_data):
""" If filename does not exist """
data = []
if not os.path.isfile(filename):
data.append(new_data)
with open(filename, 'w') as f:
f.write(json.dumps(data))
else:
""" If filename exists but empty """
if os.stat(filename).st_size == 0:
data = []
with open(filename, 'w') as f:
f.write(json.dumps(data))
""" If filename exists """
with open(filename, 'r+') as f:
file_data = json.load(f)
file_data.append(new_data)
f.seek(0)
json.dump(file_data, f)