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.
Related
I used the following line to rename my file by adding timing and remove extra space and replace it with (-)
if i would like to add extra information like lable before the timing ,
filename = ("%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()))).replace(" ", "-")
the current output looks like
testfile_2016-07-25_12:17:14.mp4
im looking to have the file output as
testfile_2016-07-25_12:17:14-MediaFile.mp4
try the following ,
filename = ("%s_%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S","Mediafile",time.localtime()))).replace(" ", "-")
what did i missed here ?
You're using the function strftime incorrectly. Strftime only takes 2 arguments and you're passing it 3.
You would need to generate the string from the time and apply some string operations to append the extra info.
If you want to add MediaFile to the end of the filename simply do something like this.
filename = ("%s_%s-MediaFile.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()))).replace(" ", "-")
filename = ("%s_%s-%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()), 'MediaFile')).replace(' ', '-')
# 'testfile_2016-07-25_10:29:28-MediaFile.mp4'
To understand better how this works and slightly improve readability, you can define your time stamp in a separate variable:
timestr = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()) # 2016-07-25_10:31:03
filename = ("%s_%s-%s" %(pfile, timestr, 'MediaFile')).replace(' ', '-')
# 'testfile_2016-07-25_10:31:03-MediaFile.mp4'
or
filename = ("%s_%s-MediaFile.mp4" %(pfile, timestr)).replace(' ', '-')
For completeness, you can also use the format() method:
filename = '{0}_{1}-MediaFile.mp4'.format(pfile, timestr).replace(' ', '-')
What you are looking for should be :
filename = ("%s_%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()),"Mediafile")).replace(" ", "-")
In your original code, the 'Mediafile' string was not in the right place : you put it as an argument of strftime(), when you should put it as one of the string to replace, in the 2nd level of parentheses.
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'
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)
I have an excel book with a couple of sheets. Each sheet has two columns with PersonID and LegacyID. We are basically trying to update some records in the database based on personid. This is relatively easy to do TSQL and I might even be able to get it done pretty quick in powershell but since I have been trying to learn Python, I thought I would try this in Python. I used xlrd module and I was able to print update statements. below is my code:
import xlrd
book = xlrd.open_workbook('D:\Scripts\UpdateID01.xls')
sheet = book.sheet_by_index(0)
myList = []
for i in range(sheet.nrows):
myList.append(sheet.row_values(i))
outFile = open('D:\Scripts\update.txt', 'wb')
for i in myList:
outFile.write("\nUPDATE PERSON SET LegacyID = " + "'" + str(i[1]) + "'" + " WHERE personid = " + "'" + str(i[0])
+ "'")
Two problems - when I read the output file, I see the LegacyID printed as float. How do I get rid of .0 at the end of each id? Second problem, python doesn't print each update statement in a new line in the output text file. How to I format it?
Edit: Please ignore the format issue. It did print in new lines when I opened the output file in Notepad++. The float issue still remains.
Can you turn the LegacyID into ints ?
i[1] = int(i[1])
outFile.write("\nUPDATE PERSON SET LegacyID = " + "'" + str(i[1]) + "'" + " WHERE personid = " + "'" + str(i[0])
+ "'")
try this..
# use 'a' if you want to append in your text file
outFile = open(r'D:\Scripts\update.txt', 'a')
for i in myList:
outFile.write("\nUPDATE PERSON SET LegacyID = '%s' WHERE personid = '%s'" %( int(i[1]), str(i[0])))
Since you are learning Python (which is very laudable!) you should start reading about string formatting in the Python docs. This is the best place to start whenever you have a question light this.
Hint: You may want to convert the float items to integers using int().
I have searched the grep answers on here and cannot find an answer. They all seem to search for a string in a file, not a list of strings from a file. I already have a search function that works, but grep does it WAY faster. I have a list of strings in a file sn.txt (with one string on each line, no deliminators). I want to search another file (Merge_EXP.exp) for lines that have a match and write it out to a new file. The file I am searching in has a half millions lines, so searching for a few thousand in there takes hours without grep.
When I run it from command prompt in windows, it does it in minutes:
grep --file=sn.txt Merge_EXP.exp > Merge_EXP_Out.exp
How can I call this same process from Python? I don't really want alternatives in Python because I already have one that works but takes a while. Unless you think you can significantly improve the performance of that:
def match_SN(serialnumb, Exp_Merge, output_exp):
fout = open(output_exp,'a')
f = open(Exp_Merge,'r')
# skip first line
f.readline()
for record in f:
record = record.strip().rstrip('\n')
if serialnumb in record:
fout.write (record + '\n')
f.close()
fout.close()
def main(Output_CSV, Exp_Merge, updated_exp):
# create a blank output
fout = open(updated_exp,'w')
# copy header records
f = open(Exp_Merge,'r')
header1 = f.readline()
fout.write(header1)
header2 = f.readline()
fout.write(header2)
fout.close()
f.close()
f_csv = open(Output_CSV,'r')
f_csv.readline()
for rec in f_csv:
rec_list = rec.split(",")
sn = rec_list[2]
sn = sn.strip().rstrip('\n')
match_SN(sn,Exp_Merge,updated_exp)
Here is a optimized version of pure python code:
def main(Output_CSV, Exp_Merge, updated_exp):
output_list = []
# copy header records
records = open(Exp_Merge,'r').readlines()
output_list = records[0:2]
serials = open(Output_CSV,'r').readlines()
serials = [x.split(",")[2].strip().rstrip('\n') for x in serials]
for s in serials:
items = [x for x in records if s in x]
output_list.extend(items)
open(updated_exp, "w").write("".join(output_list))
main("sn.txt", "merge_exp.exp", "outx.txt")
Input
sn.txt:
x,y,0011
x,y,0002
merge_exp.exp:
Header1
Header2
0011abc
0011bcd
5000n
5600m
6530j
0034k
2000lg
0002gg
Output
Header1
Header2
0011abc
0011bcd
0002gg
Try this out and see how much time it takes...
When I use full path to grep location it worked (I pass it the grep_loc, Serial_List, Export):
import os
Export_Dir = os.path.dirname(Export)
Export_Name = os.path.basename(Export)
Output = Export_Dir + "\Output_" + Export_Name
print "\nOutput: " + Output + "\n"
cmd = grep_loc + " --file=" + Serial_List + " " + Export + " > " + Output
print "grep usage: \n" + cmd + "\n"
os.system(cmd)
print "Output created\n"
I think you have not chosen the right title for your question: What you want to do is the equivalent of a database JOIN. You can use grep for that in this particular instance, because one of your files only has keys and no other information. However, I think it is likely (but of course I don't know your case) that in the future your sn.txt may also contain extra information.
So I would solve the generic case. There are multiple solutions:
import all data into a database, then do a LEFT JOIN (in sql) or equivalent
use a python large data tool
For the latter, you could try numpy or, recommended because you are working with strings, pandas. Pandas has an optimized merge routine, which is very fast in my experience (uses cython under the hood).
Here is pandas PSEUDO code to solve your problem. It is close to real code but I need to know the names of the columns that you want to match on. I assumed here the one column in sn.txt is called key, and the matching column in merge_txt is called sn. I also see you have two header lines in merge_exp, read the docs for that.
# PSEUDO CODE (but close)
import pandas
left = pandas.read_csv('sn.txt')
right = pandas.read_csv('merge_exp.exp')
out = pandas.merge(left, right, left_on="key", right_on="sn", how='left')
out.to_csv("outx.txt")