I want to include the date on to this file so it would be unity20130723.txt How do I go about it. I have this so far:
dt =datetime.datetime.now()
f=open('unity.txt', 'w')
for issue in data["issues"]:
f.write(issue ['key'])
f.write(issue['fields']['summary'])
f.write('\n')
f.close()
I love the Answers here I also made an addition to the script to give me 2 digits for the months and days. It will look like this in case any one is looking for how to.
f=open('unity{}{}{}.txt'.format(dt.year, '%02d' % dt.month, '%02d' % dt.day), 'w')
An easy way is using time.strftime.
>>> import time
>>> time.strftime('%Y%m%d')
'20130723'
>>> time.strftime('unity%Y%m%d.txt')
'unity20130723.txt'
You can access the different fields of dt using dt.year, dt.month, dt.day. So if you wanted to put the date in the name of the file you could do
f=open('unity{}{}{}.txt'.format(dt.year, dt.month, dt.day), 'w')
EDIT: Brien's answer is really elegant, I would use that in conjunction with the format code I used here.
dt = datetime.datetime.now()
f_timestamp = "".join([dt.year, dt.month, dt.day])
filename = "unity{}.txt".format(f_timestamp)
with open(filename, "w") as f:
for issue in data["issues"]:
f.write(issue ['key'])
f.write(issue['fields']['summary'])
f.write('\n')
file_name = 'Unity_%s.txt' % dt.strftime(format='%Y%m%d')
Strftime is all you need and will output something like Unity_20130723.txt
Then just do:
f=open(file_name, 'w')
You can try this:
from datetime import datetime
FORMAT = '%Y%m%d%H%M%S'
path = 'unity.txt'
data = 'your data'
new_path = '%s%s' % (path, datetime.now().strftime(FORMAT))
open(new_path, 'w').write(data)
Related
How to check if a source_file contains email addresses or md5 once you download
data2 = pd.read_csv(source_file, header=None)
tried using regrex and str.contains...but not able to figure out how to proceed
if that is checked then according to that i need to proceed for rest of the script
source_file1:
abd#gmail.com
xyz#gmail.com
source_file2:
d131dd02c5e6vrc4
55ad340609f4fw02
So far, I have tried:
if(data2['email/md5'].str.contains(r'[a-zA-Z0-9._-]+#[a-zA-Z.]+')==1): print "yes"
Try this pattern r'#\w+\.com'.
Ex:
import pandas as pd
df1 = pd.read_csv(filename1, names=['email/md5'])
if df1['email/md5'].str.contains(r'#\w+\.com').all():
print("Email")
else:
print("md5")
If I understand well the question, you have 2 files, and you want to automatically detect which one has email adresses and which one has md5?
import re
import re
with open(source_file1, 'r') as f:
line = f.readline()
while not line:
line = f.readline()
#First line not empty containing a mail address
if re.match('[^#]+#[^#]+\.[^#]+', f.readline()):
mail_source_file = source_file1
md5_source_file = source_file2
else:
md5_source_file = source_file1
mail_source_file = source_file2
mail_dataframe = pd.read_csv(mail_source_file, header=None)
md5_dataframe = pd.read_csv(md5_source_file, header=None)
Does this help?
This might work, considering the hash as a 16 alphanumeric symbols and there are no invalid emails:
with open('file.txt', 'r') as myfile:
getFile = myfile.read()
# Emails
numberOfEmails = len(re.findall(r'#(.*?).com', getFile))
print "%d email(s) found"%(numberOfEmails)
# MD5
hashFormatCnt = 0
splitFile = getFile.split()
for str in splitFile:
if re.match('^[\w-]+$', str):
if len(str) == 16:
hashFormatCnt = hashFormatCnt + 1
print "%d look like hash found"%(hashFormatCnt)
you need to be more specific.
if you want to know how email looks, you can see it here.
if you want to know how md5 looks, it usually is represented as 32 hex digits (0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f).
I need a function to generate datafile names with a suffix which must be the current date and time.
I want for the date Feb, 18 2014 15:02 something like this:
data_201402181502.txt
But this is that I get: data_2014218152.txt
My code...
import time
prefix_file = 'data'
tempus = time.localtime(time.time())
suffix = str(tempus.tm_year)+str(tempus.tm_mon)+str(tempus.tm_mday)+
str(tempus.tm_hour)+str(tempus.tm_min)
name_file = prefix_file + '_' + suffix + '.txt'
You can use time.strftime for this, which handles padding leading zeros e.g. on the month:
from time import strftime
name_file = "{0}_{1}.txt".format(prefix_file,
strftime("%Y%m%d%H%M"))
If you simply turn an integer to a string using str, it will not have the leading zero: str(2) == '2'. You can, however, specify this using the str.format syntax: "{0:02d}".format(2) == '02'.
Looks like you want
date.strftime(format)
The format string will allow you to control the output of strftime, try something like:
"%b-%d-%y"
From http://docs.python.org/2/library/datetime.html
Using str.format with datetime.datetime object:
>>> import datetime
>>> '{}_{:%Y%m%d%H%M}.txt'.format('filename', datetime.datetime.now())
'filename_201402182313.txt'
How can i get the current time in UTC time (Zulu style for hours and minutes: 0100Z) , and add it to a string so i can concatenate it
This gives me cannot concatenate string:
import datetime
utc_datetime = datetime.datetime.utcnow()
utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result: '2011-12-12-0939Z'
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_'+utc_datetime+'.txt'
And this gives me another string for the filename:
//returns: /SomeDirectory/AnotherDirectory/FilePrefix_2011-12-12 09:42:15.374022.txt
import datetime
utc_datetime = datetime.datetime.utcnow()
utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result: '2011-12-12-0939Z'
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_'+str(utc_datetime)+'.txt'
Thanks in advance
What you want to do is probably :
import datetime
utc_datetime = datetime.datetime.utcnow()
formated_string = utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result: '2011-12-12-0939Z'
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_%s.txt'% formated_string
or in a one-liner way :
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_%s.txt'%datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%MZ")
When using datetime.strftime it returns the string formatted as you need, it does not modify the datetime object.
EDIT : use %s instead of +, thanks Danilo Bargen
The strftime method of a datetime object only returns a value, but doesn't manipulate the original object. You need to save the result into the variable itself, or into a new variable.
import datetime
utc_datetime = datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%MZ")
utc_datetime //Result: '2011-12-12-0939Z'
Additionally, you shouldn't use + to concatenate several strings because of performance reasons. Use this instead:
filename = '/directory/prefix_%s.txt' % utc_datetime
You need to save the result of utc_datetime.strftime() into a variable:
>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> s=utc_datetime.strftime("%Y-%m-%d-%H%MZ")
>>> filename = '/SomeDirectory/AnotherDirectory/FilePrefix_' + s + '.txt'
>>> print filename
/SomeDirectory/AnotherDirectory/FilePrefix_2011-12-12-0946Z.txt
>>>
You're currently computing a value and throwing away the string result.
In Python v2, is there a way to get a date/time stamp and put it into creating a new text file?
IE: When I want to create a new text file and write the contents of my program to it, it will create a new text file with the time/date in it.
Thanks for any help.
import datetime
def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
return datetime.datetime.now().strftime(fmt).format(fname=fname)
with open(timeStamped('myfile.txt'),'w') as outf:
outf.write('data!')
This will prepend a timestamp to the front of the filename:
from datetime import datetime
# define a timestamp format you like
FORMAT = '%Y%m%d%H%M%S'
path = 'foo.txt'
data = 'data to be written to the file\n'
new_path = '%s_%s' % (datetime.now().strftime(FORMAT), path)
open(new_path, 'w').write(data)
import datetime
f=open("/home/rohitsai/Documents/acs.txt",'a')
f.write ("heloo"+'\t')
f.write(datetime.datetime.now().ctime())
print datetime.datetime.now()
this code will add helo as well as current date on same file. 'a' is for append mode, \t for tab space.
import datetime
open("file", "w").write(datetime.datetime.now().ctime())
open(datetime.datetime.now().ctime(), "w").write("foo")
I like just having the date in my file handles:
from datetime import date
def timeIzNow():
'''
returns current date as a string
'''
now = date.today()
full = "-" + str(now.month) + "-" + str(now.day) + "-" + str(now.year)
return full
fileN = "findGenes"
with open(fileN + timeIzNow() + ".txt", 'w') as f:
#DO STUFF
Your new file name will look like
findGenes-6-5-2013.txt
A lot of these answers are unnecessarily complicated if you just want to spit out a timestamp to a file and don't care about tweaking the format of said stamp
You can literally do it in one line:
f.write(datetime.now().__str__() + "\n")
Here I assume f is a file - so we print the string representation of datetime.now() and add a new line, because write() doesn't do that for you. (You probably already knew that though.)
Note: checked working with Python 3, I didn't test with Python 2, I'm not sure which version of the language spec you are using.
Im wrtiting a script which saves the current date and time as a filename but I get an error stating "TypeError: not all arguments converted during string formatting" I am new to Python andmay of missed something obvious. Code below:
from subprocess import Popen
import datetime
today = datetime.date.today()
today = str(today)
print today
f = open("%s.sql", "w" % (today))
x = Popen(["mysqldump", "-u", "root", "-pucsdrv", "normalisationtion"], stdout = f)
x.wait()
f.close()
You're putting the string formatting in the wrong place; it needs to be right after the string that's being formatted:
f = open("%s.sql" % (today), "w")
It's legal to not pass any formatting arguments, like you did with "%s.sql", but it's not legal to pass arguments but not the right amount ("w" % (today) passes one, but there's no string formatting in "w", so you get an error that not all of the arguments were used)
f = open("%s.sql" % today, "w")