I am running some code and I would like to save a csv file which include the current date and time in its name.
For example: I run some code now (12:24, Jan 15) and I would like to have something like
name_1224_01152021.csv
Can you tell me how to print/save this information, please?
The following code should format the name as per your requirement:
import datetime
name = f'name_{datetime.datetime.now().strftime("%H%M_%m%d%Y")}.csv'
print(name)
# prints 'name_0628_01152021.csv'
Here is the code according to your question :
from datetime import datetime
filename = datetime.now().strftime('filename_%H%M_%m%d%Y.csv')
with open(filename, "w+") as f_output:
csv_output = csv.writer(f_output)
csv_output.writerow(["row1", "row2"])
in filename you have to write your file name the output of this will be shown as
filename_0620_01152021_.csv
Something like this might be what you want :
from datetime import date
today = date.today()
# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
fname = "name_1224" + d1 + ".csv"
#fname = "name_1224" + str(d1) + ".csv"
import datetime
val_time =datetime.time.now()
now you can append name and val_time and save file with that name
You can format your date with strftime.
import datetime
filename = datetime.datetime.now().strftime('name_%H%_%d%m%Y.csv')
then you can do something like
open(filename, "w").write("blahblah")
Related
I would like to save the excel file(File Name- Stock) in python along with current date, let me know how to save it with date.
Below is the Script am using normally to save the excel files.
path=r"\C:\User\ASL - Stock Reports\Stock.xlsx"
writer=pd.ExcelWriter(path,engine='xlsxwriter')
Overall_Stock.to_excel(writer, index=False)
writer.save()
writer.close()
Thanks in advance
import datetime
import pandas as pd
now = datetime.datetime.now()
date = '{}-{}-{}'.format(now.year, now.month, now.day)
filename = 'Name_of_your_file' + '_' + date
path=r"\C:\User\ASL - Stock Reports\Stock.xlsx"
writer=pd.ExcelWriter(path, sheet_name = filename, engine='xlsxwriter')
Overall_Stock.to_excel(writer, index=False)
writer.save()
writer.close()
This should work. Let me know if it does not.
Something like this:
from datetime import datetime
curr_date = datetime.strftime(datetime.now(), '%Y_%m_%d')
Overall_Stock.to_excel(path.split('.xlsx')[0] + '_' + curr_date + '.xlsx', index=False)
I am trying to get python to automatically add the current time and date as a filename after it finishes with running the report its designed to.
Get current date from datetime module using datetime.date.today(), use strftime() to parse it to your required format and add it to your filename string.
import datetime
filename = 'XYZ Report {0}.txt'
current_date = datetime.date.today().strftime('%d %b %Y')
filename = filename.format(current_date)
# filename = XYZ Report 19 Sep 2018.txt
with open(filename) as file_obj:
# File writing logic
Answer is:
import time
import xlwt
import csv
date_string = time.strftime("%Y%m%d %H.%M")
if saving to CSV document
data_output = []
with open('C:\\Users\\Desktop\\File Name' + date_string + '.csv', 'a+') as f:
w = csv.writer(f, delimiter=',')
for data in data_output:
w.writerow(data)
f.close()
if saving to Excel document
df.to_excel('C:\\Users\\Desktop\\File Name' + date_string + '.xlsx')
if saving to Txt document
df.to_csv('C:\\Users\\Desktop\\File Name' + date_string + '.txt')
I want to change csv name (in this case Example.csv) to a specific name: date time name. I have a library called from datetime import datetime
This is my sentence to create a cvsFile:
with open('Example.csv', 'w') as csvFile:
I want that my output to be:
20180820.csv
20180821.csv
20180822.csv ... etc
And if I run more that one time in the same day, I want that my output to be:
20180820.csv (First time that I run the script)
20180821(2).csv (Second time run)
... etc
Something like this:
import pandas as pd
import datetime
current_date = datetime.datetime.now()
filename = str(current_date.day)+str(current_date.month)+str(current_date.year)
df.to_csv(str(filename + '.csv'))
Since you know how to create the file name you just have to check whether it already exists or not :
def exists(filename):
try:
with open(filename) as f:
file_exists = True
except FileNotFoundError:
file_exists = False
return file_exists
name = 'some_date.csv'
c = 0
while exists(filename):
c += 1
name = 'some_date({}).csv'.format(c)
# do stuff with name
Please find a solution if you can manage a 'progressive' variable taking track of the files. Otherwise you need to check the disk content and it might be rather more complex.
import datetime
progressive = 0
today = datetime.date.today()
todaystr = str(today)
rootname = todaystr
progressive += 1
if progressive > 1:
rootname = todaystr + '_' + str(progressive)
filename = rootname + '.csv'
Count the number of files in the directory with the same date in its name and use that information to create the file name. Here is a solution for both your problems.
import datetime
import os
now = datetime.datetime.now().strftime("%y%m%d")
# count the number of files already in the output dir with date (now)
count = len([name for name in os.listdir('./output/') if (os.path.isfile(name) and now in name)])
csv_name = './output/' + now
if count > 0:
csv_name = csv_name + "(" + str(count+1) +")"
csv_name = csv_name + ".csv"
with open(csv_name, 'w') as csvFile:
pass
Good Luck.
I found the solution:
Only take the real time in a variable, and then concatenate with .csv (and also I put this csv output in a specific folder called output). Finally I open the csvFile with the variable name.
> now = datetime.now().strftime('%Y%m%d-%Hh%M')
> csvname = './output/' + now + '.csv'
> with open(csvname, 'w') as csvFile:
I can not do the second part of my problem. I want that if I run more than one time the code the date time name change or add (2), (3)... etc.
I have the following Python 2.7 code. The aim is to read the csv file and run through the script for each row in the CSV file.
The CSV file looks like this (no headers, all filenames in column A - one file name per row, not comma separated)
ftp_abc_REFRESH_a
ftp_dep_a
The script works for the first file, but fails on the second file with the following error:
timestamp = oupload.stat(file).st_atime
UnboundLocalError: local variable 'file' referenced before assignment
Any help is appreciated. Thanks :)
The script:
def myscript(ofile):
import time
import pysftp
import sys
import os
from datetime import datetime
import calendar
import zipfile
import re
oupload = pysftp.Connection(host="hostbcd", username="admin", password="abcs")
d = datetime.utcnow()
unixtime=calendar.timegm(d.utctimetuple())
month = datetime.now().strftime("%m")
string = ofile+month+".*\.txt$"
possibleFiles = oupload.listdir("/")
for filename in possibleFiles:
filedate = re.search(string, filename)
if filedate:
file = filename
timestamp = oupload.stat(file).st_atime
#if timestamp > unixtime - 54050 - 30 days
if timestamp != unixtime:
newtime=unixtime + 1800
abmfile='filename_'
zipname = abmfile+str(newtime)+'.sync.zip'
create_zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
oupload.get(file,file)
oupload.close()
newfilename = abmfile+str(newtime)+'.sync'
os.rename(file, newfilename)
create_zip.write(newfilename)
create_zip.close()
else:
print "No files found"
import csv
with open("data.csv", 'r') as csv_file:
reader = csv.reader(csv_file)
for row in reader:
ofile = row[0]
result = myscript(ofile)
The error shows you pretty much everything :
UnboundLocalError: local variable 'file' referenced before assignment
This means you are trying to use something that has not been set earlier.
The only moment you would initialize file is into your if-statement if filedate. You are not passing the condition, hence the error and the un-initialiazed file object.
This is my example path: 'c:\Data\2015-08-01'
Currently I'm getting all the files inside on one(1) specific date, but my goal is to get the files with date range of file folder. Example is to get 2015-08-01 to 2015-08-05' just like the BETWEEN query in MySQL
import os
import os.path
import tempfile
dateStart = '2015-08-01'
dateEnd = '2015-08-05'
year = dateStart[0:4]
yearMonth = year + '_' + dateStart[5:7]
pathDir = 'c:\\Data'
date_folder = pathDir + '\\' + dateStart
count = 0
for filefolder in os.listdir(date_folder):
filefolder = date_folder + "\\" + filefolder
for file in os.listdir(filefolder):
if "txt" in file:
filename = filefolder + "\\" + file
print filename
#Output of this, is all text files for this date only '2015-08-01'
Its hard for me to loop to pull files for date range e.g. '2015-08-01' to '2015-08-05'. How to do this?
Note that there is a folder after my dates and the textfiles are in the last. and the textfile containing on that folder is my point to get. so that from my old code I used this: filefolder = date_folder + "\" + filefolder to get the text in 1 date only.
Here is my sample real path data:
\\10.81.67.162\DLCx Logs\DLCx02\2015\2015_08\2015-08-01\Folder\data.text
and if I will get the range from 2015-08-01 to 2015-08-01. this will be the output:
\\10.81.67.162\DLCx Logs\DLCx02\2015\2015_08\2015-08-01\Folder\data.text
\\10.81.67.162\DLCx Logs\DLCx02\2015\2015_08\2015-08-02\Folder\data.text
\\10.81.67.162\DLCx Logs\DLCx02\2015\2015_08\2015-08-03\Folder\data.text
\\10.81.67.162\DLCx Logs\DLCx02\2015\2015_08\2015-08-04\Folder\data.text
\\10.81.67.162\DLCx Logs\DLCx02\2015\2015_08\2015-08-05\Folder\data.text
Here is my approach: start with separate year, month, day and build the date:
import glob
import os
pattern = os.path.join(r'C:\Data', '{}-{:02}-{:02}', '*', '*.txt')
year, month = 2015, 8
start_day, end_day = 1, 5
for day in range(start_day, end_day + 1):
wildcard = pattern.format(year, month, day)
for filename in glob.glob(wildcard):
print filename
The datetime module makes doing date arithmetic, comparisons, as well as converting them to or from strings relatively easy.
Here's how it could be used to do what you're trying to accomplish (at least according to your most recent comments):
from datetime import datetime, timedelta
from glob import glob
from os import path
DATE_FORMAT = '%Y-%m-%d'
SUBFOLDER_PATH_FORMAT = r'%Y\%Y_%m\%Y-%m-%d\Folder'
pathDir = r'\\10.81.67.162\DLCx Logs\DLCx02'
dateStart = '2015-08-01'
dateEnd = '2015-09-01'
start_date = datetime.strptime(dateStart, DATE_FORMAT).date()
end_date = datetime.strptime(dateEnd, DATE_FORMAT).date()
delta_one_day = timedelta(days=1)
date = start_date
while date <= end_date:
subfolder_path = date.strftime(SUBFOLDER_PATH_FORMAT)
data_folder = path.join(pathDir, subfolder_path)
if path.isdir(data_folder):
for filename in glob(os.path.join(data_folder, '*.txt')):
print filename
date += delta_one_day
It is easiest to convert your dates to date objects. You can then just compare them. See example below:
#!/usr/bin/python
import os
import os.path
import tempfile
import datetime
import re
dateStart = '2015-08-03'
dateEnd = '2015-08-05'
# helper function to convert date strings to date objects
def make_dt(ds):
return datetime.date(int(ds[0:4]), int(ds[5:7]), int(ds[8:10]))
# convert date string to date object
dt_start = make_dt(dateStart)
dt_end = make_dt(dateEnd)
pathDir = '.'
if __name__ == "__main__":
for folder in os.listdir(pathDir):
# only folders that match date format yyyy-mm-dd
if re.match("[0-9]{4}-[0-9]{2}-[0-9]{2}", folder):
# convert folder name to date object
dt_folder = make_dt(folder)
if (dt_folder <= dt_end) and (dt_folder >= dt_start):
print "folder %s is between start [%s] and end [%s]" % (folder, dateStart, dateEnd)