By using subprocess module , how can we create a directory with today's date and time as directory name ?
I can follow one process , like assigning todays date to a variable in the the python and use that variable as reference to create a directory.
And I am using windows as my target machine.
but is there any other best ways I could follow ?
Thanks
If you think that you can rely upon your system's timezone setting, you may use built in date command (on Unix-like systems) in a way like this:
os.system("mkdir `date +%Y-%m-%d_%H:%M:%S`")
Though, there are other solutions, like to use os.mkdir().
Try it out.
The following will create a folder with the current date as its name. See the 'man date' to adjust the output to your liking.
import subprocess
p = subprocess.Popen('mkdir "$(date)"', shell=True)
Related
This is relatively simple matter but for some reason I cannot find a way to get the full path of the windows temp directory via python or to find similar request already posted in stack overflow community.
I'm using tempfile.gettempdir() command but it seems there is no way to capture the full path and it returns the short version:
'C:\Users\SVETLO~1\AppData\Local\Temp'
This overall works but there is an important part of the script later on which doesn't and it requires the full temp dir path, which is:
C:\Users\SvetlozarDraganov\AppData\Local\Temp\
Does anyone knows how to get the full absolute path to windows-temp folder with python?
Thanks in advance.
Svet
Edit-1:
I'm testing the %fA suggestion from CMD but for some reason, it doesn't work. If I'm using %sA attribute it actually returns the short path version:
CMD: for %A in ("C:\Users\SvetlozarDraganov\AppData\Local\Temp") do #echo %~sA
OUTPUT: C:\Users\SVETLO~1\AppData\Local\Temp
The %fA attribute however doesn't return the full path:
CMD: for %A in ("C:\Users\SVETLO~1\AppData\Local\Temp") do #echo %~fA
OUTPUT: C:\Users\SVETLO~1\AppData\Local\Temp
Speaking of full absolute path, you already have it.
The "short version" is the 8.3 filename that exists before VFAT and the "full path" as you meant it is the "long filename" or LFN. They are interchangable so long as accessing the file in concern.
In Windows command prompt, you can use parameter expansions to convert from short to long and back. See the solution here for an example (replace %~sA in the answer with %~fA in your case). So you can make use of that and call the command with subprocess.run() to read the output.
I can't recall Python has a built-in function for doing this conversion. But Windows API does: You may want to see how this solution for converting LFN to short filename, which in your case, the function should be GetLongPathName() instead.
I found a out-of-the-box solution to my question in python os module:
https://docs.python.org/2/library/os.path.html#os.path.realpath
It returns the long-version path!
Thanks to everybody!
When i was importing my photos from my ipad to my hard disk i mistakenly imported them with the creation date of that day.
So now the true date for each photo is the modified date of it. I basically use this command to Setfile -d "$(GetFileInfo -m _FILE_PATH_)" _FILE_PATH_ to set the creation date of my photo to its modified date. But i was wondering if there is a way to put this command line in a python script where i can batch select multiple photos to preform this action.
Also, since if I open any photo the system will change its modified date, the only way that i can guess which date some photos belong to is by sorting them by name to see which date the photos before and after it belong to.
Any ideas on how I can write a script that deduces the real date of photos which have dates larger than a specific date based on the photos before and after it?
For example, you see in the screenshot that there is a photo from May 8 between two photos from October 5, so clearly it should be taken on October 5 as well.
But unfortunately sometimes the modified date of the photos before and after a photo are also wrong so I think the program has to look for the smallest date before and after the photo to deduce the real date.
UPDATE
I wrote this code on the python and it works fine for single files when I drag and drop them into the terminal to give the program the path. Im wondering if there is a way to do this with multiple files.
from subprocess import call
import os
path = input("enter filepath: ")
info = '"$(GetFileInfo -m '+ path + ')" '
command = 'Setfile -d ' + info + path
print('Setfile -d ' + info + path)
call(command, shell=True)
Not requiring interactive input is probably a crucial improvement so that you can run this on a large number of files at the same time. The way to do that in Python is with sys.argv.
Also, rather than subprocess.call, use subprocess.check_call (or subprocess.check_output to get the output) so that you can avoid invoking a shell, and check that the subprocess completed successfully. (There will be a traceback if not; if you want something more user-friendly, wrap it in try/except. Probably look for existing questions before posting another question asking for help with that.)
from subprocess import check_output, check_call
from sys import argv
for path in argv[1:]:
date = check_output(['GetFileInfo', '-m', path])
check_call(['Setfile', '-d', date, path])
Use it like
python3 script.py file1.png /path/to/file2.png ../elsewhere/file3.png ...
(Relative paths are resolved starting from your current working directory; no path resolves to the current directory.)
My requirement is to delete the previous day directory and create a new directory in the format like as given in the below screen.
We generally make a directory in a below format taking into account the day and the date.
For example:
TP1_<TODAY_DAY>_<TODAY_DATE> TP1_TUE_19JUN2018.
How can this be achieved?
to get it into a variable on linux shell you can use the following:
export mydate=$(date +%a_%d%b%Y|tr [a-z] [A-Z])
then you can use the variable as part of cd, mkdir or any other command, i.e.
echo TP1__ TP1_$mydate
will give as result, please note that I used it on a Italian Cent OS Linux,
TP1__ TP1_MAR_19GIU2018
I used the following function to created dirctory based on today date ,
#!/usr/bin/python
import time, datetime, os
today = datetime.date.today()
todaystr = today.isoformat()
os.mkdir(todaystr)
so the out put will be
/2015-12-22/
what i'm looking to is adjust the structure which is create dirctories structure based on day date as following
/2015/12/22
/2015/12/23
etc
when ever i run the function it will check the date and make sure the folder is exist other wise will create it ..
any tips to follow here ?
Consider using strftime instead. Which you can use to defined a format to your liking. You will also need to use os.makedirs as described by #Valijon below.
os.makedirs(time.strftime("/%Y/%m/%d"), exist_ok=True)
You can also append a given time to create a time-stamp in the past or in the future.
time.strftime("/%Y/%m/%d", time.gmtime(time.time()-3600)) # -1 hour
Also note that your path is a bit dangerous, unless you want to create folders directly under the root partition.
Note that makedirs will raise an exception by default if the directory already exists, you can specify exist_ok=True to avoid this, read more about it in the docs for os.makedirs.
Since Python 3.4, the module pathlib was Introduced which offers some directory and file creation features.
import time
import pathlib
pathlib.Path(time.strftime("/%Y/%m/%d")).mkdir(parents=True, exist_ok=True)
Just change os.mkdir to os.makedirs
os.makedirs(today.strftime("%Y/%m/%d"))
I would like to know how to get the path where the script is stored with argparse, if possible, because if I run the script from another path (I have the path of the script in the %PATH% variable) it uses by default the relative path.
I know that I can obtain it using:
import sys
sys.argv[0]
but I would like to know if it is possible to acess it directly from the argparse module.
Thanks
Edit: I have my reply and I am satisfied.
To explain better the question: I have a script called mdv.py that I use to transform markdown files into html. I would like to call it from any location in my computer.
The script is in:
c:\Python27\markdown
in this path there are other files and a folder templates that I use to generate my HTML (a default stylesheet and files for header, body and footer).
These files are in:
C:\Python\27\markdown\markdown\templates
When I call the script from a non standard path, for example c:\dropbox\public it looks in c:\dropbox\public\templates for these files and not in c:\python27\markdown\templates where they are saved.
Ihope to have better explained. Sorry I'm not a native english speaker.
I think you are looking for the prog parameter; you can interpolate sys.argv[0] into your help strings with %(prog)s.
The value for prog can be set when creating the ArgumentParser() instance; it is the first parameter:
parser = argparse.ArgumentParser('some_other_name')
and can be retrieved with the .prog attribute:
print(parser.prog) # prints "some_other_name"
However, argparsecalls os.path.basename() on this name, and does not store the directory of the program anywhere.