How do I make the filepath dynamic. I have to pick info from 7 spreadsheets and I have to just daily change the dates in these file paths. How can i declare the date and call the date in a string.
date = 20200607
filepath = HKTR Report\06. June**20200605**\Summary006T-CTRD2603-FX-20200605.csv"
The two dates in the file path have to be replaced with date declared making the filepath dynamic.
Kindly assist.
Welcome to Stack Overflow!
The path you have listed is peculiar in that it contains star characters which are not usually used in pathnames.
That said, try using this code:
from datetime import date
d = date.today()
date_str = d.strftime('%Y%m%d')
print(date_str)
filepath = f'HKTR Report\\06. June**{date_str}**\\Summary006T-CTRD2603-FX-{date_str}.csv'
print(filepath)
which generates this output:
20200608
HKTR Report\06. June**20200608**\Summary006T-CTRD2603-FX-20200608.csv
Related
I am trying to run this script so that it creates a .txt file based on the date.
#Importing libraries
import os
import sys
#Selecting time and methods
from time import gmtime, strftime
from datetime import datetime
#Fortmatting date & printing it
date = datetime.now().strftime("%Y_%m_%d-%I:%M_%p")
#Creating the name of the file, plus the date we created above
newFile = ("Summary_" + date) + '.txt'
#Creating the filepath where we want to save this file
filepath = os.path.join('C:\\Users\\myUser\\Desktop\\myFolder', newFile)
#If the path doesn't exist
if not os.path.exists('C:\\Users\\myUser\\Desktop\\myFolder'):
os.makedirs('C:\\Users\\MyUser\\Desktop\\myFolder')
f = open(filepath, "w")
Everything works, however, the file gets created as a File and not a .txt file.
I am not sure if I am not concatenating the strings correctly, or if there is an additional step I need to take.
I noticed that if I type anything after the date string, it doesn't get added to the end of the file.
If I type the string manually like this, then it works just fine:
filepath = os.path.join('C:\\Users\\myUser\\Desktop\\myFolder', "Summary_DateGoesHere.txt")
Am I missing something in my script?
I appreciate the assistance.
The issue here is , Windows won't allow to create a file name having colon :
Here, your filename variable is - "Summary_2022_05_05-11:24_AM.txt". As colon is not allowed, its truncating after 11, and creating a file name with just Summary_2022_05_05-11.
To fix this, you can use underscore or hyphen before minutes field like this:
date = datetime.now().strftime("%Y_%m_%d-%I_%M_%p")
I have say a/b/c/date/Xyz.txt how can I pick up the path dynamically, date is changing randomly. Other directory fields remains the same like a/b/c/dateIsChanging/Xyz.txt
Someone is adding file random date directory, how can I get the path, each time when it is added
a/b/c/dateIsChanging/Xyz.txt here in directory under random chosen by the user, I want to pick it up whatever date comes in
Date in YYYYMMDD formate
This is an example of what one would do:
import os
import datetime as dt
# create a date for folder name
date_part = dt.datetime.today().strftime('%Y-%m-%d')
# generate the folder path
the_path = os.path.join('C:\\','test',str(date_part),'file_name.txt')
print(the_path)
the output:
C:\test\2022-03-24\file_name.txt
Obviously, would need to adjust for your particular operating system and date format.
I'm trying to solve a problem at work, I am not a developer but work in general IT operations and am trying to learn a bit here and there, so I may be way off right now with what I'm trying to do here. I've just been utilizing online resources, here and a little bit from the book Automate the Boring Stuff with Python. Here is my objective:
I have two files that are automatically placed in a folder on my computer every morning at the same time using a post processor, and I need to add yesterday's date to the end of the file names before I upload them to an FTP server which I have do each morning around the same time. I am trying to write a Python script that I can somehow schedule to run each morning right after the files are placed in the folder, which will append yesterday's date in MMDDYYYY format. For example, if the files are called "holdings.CSV" and "transactions.CSV" when they are placed in the folder, I need to rename them to "holdings01112022.CSV" and "transactions01112022.CSV". I only want to rename the new files in the folder, the files from previous days with the dates already appended will remain in the folder. Again, I'm a total beginner, so my code may not make sense and there may be superfluous or redundant lines, I'd love corrections... Am I going down the right path here, am I off altogether? Any suggestions?
import os, re
from datetime import date
from datetime import timedelta
directory = 'C:\Users\me\main folder\subfolder'
filePattern = re.compile('%s.CSV', re.VERBOSE)
for originalName in os.listdir('.'):
mo = filePattern.search(originalName)
if mo == None:
continue
today = date.today()
yesterday = today - timedelta(days = 1), '%M%D%Y'
for originalName in directory:
newName = originalName + yesterday
os.rename(os.path.join(directory, originalName), os.path.join(directory, newName))
Any help is appreciated. Thanks.
Here's a short example on how to code your algorithm.
import pathlib
from datetime import date, timedelta
if __name__ == '__main__':
directory = pathlib.Path('/Users/cesarv/Downloads/tmp')
yesterday = date.today() - timedelta(days=1)
for file in directory.glob('*[!0123456789].csv'):
new_path = file.with_stem(file.stem + yesterday.strftime('%m-%d-%Y'))
if not new_path.exists():
print(f'Renaming {file.name} to {new_path.name}')
file.rename(new_path)
else:
print(f'File {new_path.name} already exists.')
By using pathlib, you'll simplify the handling of filenames and paths and, if you run this program on Linux or macOS, it will work just the same.
Note that:
We're limiting the list of files to process with glob(), where the pattern *[!0123456789].csv means "all filenames that do not end with a digit before the suffix (the [!0123456789] represents one character, before the suffix, that should not - ! - equal any of the characters in the brackets)." This allows you to process only files that do not contain a date in their names.
The elements given by the for cycle, referenced with the file variable, are objects of class Path, which give us methods and properties we can work with, such as with_stem() and stem.
We create a new Path object, new_path, which will have its stem (the file's name part without the suffix .csv) renamed to the original file's name (file.name) plus yesterday in the format you require by using the method with_stem().
Since this new Path object contains the same path of the original file, we can use it to rename the original file.
As you can see, we can also check that a file with the new name does not exist before any renaming by using the exists() method.
You can also review the documentation on pathlib.
If you have any doubts, ask away!
Are you running to any issue? If all you want is to get the csv file you can simplify your code by using one if statement instead of using regex. You also need to convert your date to string before adding it to your file name. (i.e: newName = originalName[:-3] +str(yesterday)).
If this code didnt solve your problem please mention the error that you are receiving to make it easier for others to help you.
Here is my suggestion to eliminate possible errors without knowing what type of error you are getting.
import os, re
from datetime import date
from datetime import timedelta
directory = 'C:/Users/me/main folder/subfolder'
for originalName in os.listdir(directory):
print(f'original name is = {originalName}')
if originalName[-3:].lower() =='csv':
today = date.today()
yesterday = today - timedelta(days = 1)
yesterday_file_name = originalName[:-4]+yesterday.strftime("%m%d%Y")+'.csv'
os.rename(os.path.join(directory, originalName), os.path.join(directory, yesterday_file_name))
#print('formatted file names are')
#print(yesterday_file_name)
#here is the sample output
#original name is = holdings.csv
#formatted file names are
#holdings01112022.csv
#original name is = transactions.CSV
#formatted file names are
#transactions01112022.csv
I have some thousand files and I need to rename them from a Julian date name to Calender date name.
e.g., 2000137.tif to 2000-05-16.tif
What you need is strptime and strftime from the datetime module.
Demo:
import datetime
print(datetime.datetime.strftime(datetime.datetime.strptime('2000137', '%Y%j'),
'%Y-%m-%d'))
displays
2000-05-16
Just iterate on your file names and transform them...
I was able to do this by using the following code:
import os
import datetime
path = r"directory"
for i in os.listdir(path):
filename = os.path.splitext(i)[0]
new = (datetime.datetime.strftime(datetime.datetime.strptime(filename, '%Y%j'),'%Y-%m-%d'))
fileout = new + ".tif"
os.rename(i,fileout)
I have a text file that is generated everyday and is named in the following format: "year-month-date.txt" (e.g. 2016-08-25.txt).
Now I would like to open the text file with python and read some data from it. But I would like to do this without manually changing the name of text file inside the code everytime (remember the name of text file changes everyday).
So far I have (line 6 is is the part that needs fixing):
#1 Get today's date
import datetime
todays_date=datetime.date.today()
print(todays_date)
#2 Import info from a text file that is named as today's date
filename=todays_date.txt
fin=open(filename,'r')
Line1list=fin.readline()
print(Line1list)
You will have to extract a string in the correct format from todays_date.
Use strftime for that (see the docs):
filename = todays_date.strftime('%Y-%m-%d') + '.txt'
Full example:
import datetime
todays_date = datetime.date.today()
filename = todays_date.strftime('%Y-%m-%d') + '.txt'
print(filename)
>> 2016-08-25.txt
filename should be a string, you are now trying to access the attribut .txt of todays date...
replace by:
todays_date=datetime.date.today()
filename = str(todays_date)+'.txt'
Also make sure that todays_date exactly matches the name of the txt file, you may need to shuffle the days, months and years. The above only works if the file is indeed something like '2016-08-25.txt'