-1

I am a novice in python. My question relates to creating a dynamic path in python and there are multiple such posts such as How to create dynamic file sending algorithm with flask and How do I dynamically set the path of a file Python?. But the context in these is slightly different from mine. I need to create a new folder for each year and then save the output csv for each week for that year. I am making a mistake in dynamically setting y after E:\ and getting the following error.

Please suggest how can I parametrize the year in the folder path. Thanks.

def download_data(y):
    Parallel(n_jobs=1)(delayed(get_bulk_patent_data)(y, w, output_file="E:\\y\\df"+str(y)+"w"+str(w)+"a.csv") for w in range(1, 3))

YEARS = [2021,2022]

for y in YEARS:
    download_data(y)

FileNotFoundError: [Errno 2] No such file or directory: 'E:\y\df2021w1a.csv'

  • What exactly is going wrong with this code? If there's an error, we need to see the full traceback message. If it's simply not doing what you expected, we need to know what it actually did, and what you expected. – jasonharper Jun 24 '22 at 16:02
  • @jasonharper - Thanks, I have added the error message which says no such file/directory found. This is because it is not taking y = 2021 or 2022. – PhD Student Jun 24 '22 at 16:17
  • 1
    So you wanted the filename to be `E:\2021\df2021w16a.csv`? You'd need to replace that first `y` with `+str(y)+`, exactly as you did within the filename part of the path. – jasonharper Jun 24 '22 at 16:22
  • Thanks for the quick help, @jasonharper! Now it is giving the same error and has replaced y with +str(y)+ in the path. I tried with str(y) also. But still same error. – PhD Student Jun 24 '22 at 16:35
  • You might be having trouble making a string. It's hard to tell whats going on with that second line of code. I suggest you take a look at [f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) if you are using a new enough version of Python. `output_file=f"E:\\{y}\\df{y}w{w}a.csv"`. Stuff in curly braces is evaluated and string formatted. You could also look into the string interpolation character `output_file="E:\\%d\\df%dw%da.csv" % (y,y,w)`. Or even [str.format](https://docs.python.org/3/library/stdtypes.html#str.format) – bfris Jun 25 '22 at 00:39

1 Answers1

1

I figured out the right way - instead of y, I should use "+str(y)+" in the folder path. Now the code is working fine.