Use a variable as a name for a directory - python

I'm trying to code a script in python that creates a folder entitled the current timestamp, but don't really know the syntax to do it. So far I have this:
timestamp = int(time.time()) #fetches timestamp
if not os.path.exists([timestamp]): #creates new folder titled the current timestamp
os.makedirs([timestamp])
os.chdir([timestamp]) #navigates to new folder
When I run this, I run into errors.
P.S. I am a beginner, please don't bite.

The timestamp needs to be converted to a string. and then that string need to be passed as the argument to the os functions:
timestamp = str(int(time.time())) #fetches timestamp
if not os.path.exists(timestamp): #creates new folder titled the current timestamp
os.makedirs(timestamp)
os.chdir(timestamp) #navigates to new folder

Related

How to save pandas dataframe as a json file with a different name on each run

I want to run an algorthim I've made to create a .json file of a pandas dataframe, but since it is saving in the same file I have to change the name by hand everytime. How do I make it so that everytime I run the script it saves as a different name without me changing it by hand.
Here is how I've written it right now.
df2.to_json('Desktop/Thesis_Brainstorm/Thesis_Code/Office_Context/Office_15.json')
How I've tried to write it but hasn't worked.
TodaysDate = str(time.strftime("%Y-%m-%d %X")).replace(":", "")
run = 'rand_search_' + TodaysDate
df2.to_json('Desktop/Thesis_Brainstorm/Thesis_Code/Office_Context/' + run + '.json')
Was hoping it would save the output as a new name as to not override the previous run.
Maybe this could help you:
from datetime import datetime
file_name = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")+".json"
path = "Desktop/Thesis_Brainstorm/Thesis_Code/Office_Context/"
path+file_name
df2.to_json(path+file_name)
Note: you must to take care about you path. If it is not correctly set could throw an error.

How do I read specific characters of filename in Python 2.7

Lets say I have a bunch of folders/files with a name like
abc_06082018
where the numbers are the date it was created but they are different for each folder, however the abc_ stays the same for every name.
How do I only read after the abc_ and up until 8 number in?
BTW: The folder is the current working directory of the python 2.7 program, so i'm using os.getcwd() and saving it to a variable most likely as a string. The idea is to get the date from the cwd and make a file in the cwd in the form of
newfile_06082018.txt
where the numbers are taken from the name of the cwd
Thank you!
The name of the folder is in a string - just use normal string manipulation! .partition() is your friend.
folder = os.getcwd()
absolute_folder = os.path.abspath(folder)
only_folder_name = os.path.basename(absolute_folder)
prefix, sep, date_suffix = only_folder_name.partition('_')
filename = 'newfile_{date}.txt'.format(date=date_suffix)

How to modify a .pd file from python

I have a .pd file called 'missing' on my computer. The path is C:\me\Desktop\missing.pd
Inside this file there is just dates. I have an algo which create and populate this 'missing.pd' with dates everytime I run it. My algo basically create a dataframe with inside some dates, sometime empty and then create the missing.pd file on my computer and add the dates.
What I am trying to do is to not recreate everytime the missing.pd file (that's what my code do so far).
I want to say to my code :
if C:\me\Desktop\missing.pd exist, then check inside if the dates of my created dataframe are already here, if no add the ones which are not already here, if missing.pd do not exist, create it and fill it with the dates.
so far for this part of the code, it is :
path = r"C:\me\Desktop\missing.pd"
missing = pd.DataFrame(missing)
missing.to_pickle( os.path.join(path,"%s_missing.pd"%(country)))
You can use os.path.isfile(filename) to check if the file exists. Documentation here.
import os.path
if os.path.isfile(path):
"""Your date checking code here."""

Python - How can I create multiple folders in a newly created directory?

I'm very new to this, Im essentially trying to create a script for working on feature films so that everyday I can have a new set of folders made for that specific shoot day that I can the offload files too.
So far I have been able to have a Folder made with the users input of which shoot day they are on and then add the actual date to that file name.
But where I am stuck is trying to add folders within this newly created folder.
print ('')
print '\033[4m' + "Hello, Please select a shoot day to begin - this only works up until 12pm" + '\033[0m'
import os
import sys
import time, datetime
today = datetime.date.today() # get today's date as a datetime type
todaystr = today.isoformat() # get string representation: YYYY_MM_DD
# from a datetime type.
print('')
user_input = raw_input('\033[1m' + 'Enter Shoot Day Here -' + '\033[0m')
path1 = user_input
if not os.path.exists(path1):
os.makedirs(path1 +'_' + todaystr)
So this created me a folder called 015_2016-12-24. I then want to be able to add several folders with folders inside of these folders.
Just trying my best here sorry if this is a dumb question. Thanks for any help !
os.makedirs(path1 +'_' + todaystr+'/'+name of subfolder)
this will allow you to create subfolder for your newly created folder

How to change modified time for folder?

I am taking zip file as input which contains multiple files and folders,I am extracting it and then I want to change the last modified time of each content in zip to some new date and time set by user.
I am using os.utime() to change the date and time, but changes get reflected only to the files and not to the folders inside zip.
timeInStr = raw_input("Enter the new time =format: dd-mm-yyyy HH:MM:SS -")
timeInDt=datetime.datetime.strptime(timeInStr, '%d-%m-%Y %H:%M:%S')
timeInTS=mktime(timeInDt.timetuple())
epochTime=(datetime.datetime(timeInDt.year, timeInDt.month, timeInDt.day, timeInDt.hour, timeInDt.minute, timeInDt.second)-datetime.datetime(1970,1,1)).total_seconds()
z=zp.ZipFile(inputZipFile,"a",zp.ZIP_DEFLATED)
for files in z.infolist():
z.extract(files, srcFolderName)
fileName=files.filename
new= fileName.replace('/',os.path.sep)
correctName= srcFolderName+os.path.sep+new
print correctName
if(correctName.endswith(os.path.sep)):
correc=correctName[:-1]
print correc
os.utime(correc, (timeInTS, timeInTS))
else:
os.utime(correctName, (timeInTS, timeInTS))
I am using Python 2.7 as platform
Base to the directory permission is this question on SO. The directory only changes its timestamp when the directory itself changes for ex: when you create a new file in it. So to update the timestamp of folder you can create a temp file and then delete it. There should be a better way but till you find it you can manage using this.
I ran into a similar problem. Here is the code I used to get past the issue.
As user966588 stated, the directory's timestamp is updating as the directory changes.
In the post I linked, I held onto any directory metadata updates until after my directory was fully-populated in order for the timestamp change to stay.

Categories