Reputation: 75
I need create multiple files with different names but I recive data each seconds then I need save this data in each file with diferent names but my only code makes a file and when you receive another data this over write the existing file and not create another.
This is my code:
name= datetime.utcnow().strftime('%Y-%m-%d %H_%M_%S.%f')[:-3]
filename = "Json/%s.json"% name
def get_json():
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("Hello")
def net_is_up():
while(1):
response = os.system("ping -c 1 " + hostname)
if response == 0:
print "[%s] Network is up!" % time.strftime("%Y-%m-%d %H:%M:%S")
#read_json()
get_json()
else:
print "[%s] Network is down :(" % time.strftime("%Y-%m-%d %H:%M:%S")
time.sleep(60)
Upvotes: 1
Views: 6725
Reputation: 75
This is the answer:
def get_json():
name= datetime.utcnow().strftime('%Y-%m-%d %H_%M_%S.%f')[:-3]
filename = "Json/%s.json"% name
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("Hello")
def net_is_up():
while(1):
response = os.system("ping -c 1 " + hostname)
if response == 0:
print "[%s] Network is up!" % time.strftime("%Y-%m-%d %H:%M:%S")
#read_json()
get_json()
else:
print "[%s] Network is down :(" % time.strftime("%Y-%m-%d %H:%M:%S")
time.sleep(60)
Upvotes: 0
Reputation: 60143
Move these lines inside the get_json
function:
name = datetime.utcnow().strftime('%Y-%m-%d %H_%M_%S.%f')[:-3]
filename = "Json/%s.json"% name
As it stands now, filename
is only calculated once, when you start this script. You need to do it each time you're going to save a file.
Upvotes: 1