4

I have requirement where I am reading a string from json file and assign values to it to make it as a configurable file name.

String I am reading from json:

data_file_format = "sourcesystem_batchid_extractname_loadtype" 

I have variable which holds the values in my code like

sourcesystem ="xyz" batchid = "101" extractname = "abc" loadtype = "Delta" 

so my data_file_format should yeild value like

data_file_format = "xyz_101_abc_Delta" 
1
  • See this post, particularly this answer. Commented Dec 29, 2018 at 7:11

6 Answers 6

7

There are multiple methods to do that.:

fstring

data_file_format = f'{sourcesystem}_{batchid}_{extractname}_{loadtype}' 

or using .format

data_file_format = '{}_{}_{}_{}'.format(sourcetype,batchid,extractname,loadtype) 
Sign up to request clarification or add additional context in comments.

Comments

2
sourcesystem ="xyz" batchid = "101" extractname = "abc" loadtype = "Delta" data_file_format="_".join([sourcesystem,batchid,extractname,loadtype]) #or #data_file_format=sourcesystem+'_'+batchid +'_'+extractname+'_'+loadtype print(data_file_format) 

Comments

2

So, you need to dynamically generate a file name based on an input data_file_format. Can you store your data in a dict instead of separate variables?

data_file_format = "sourcesystem_batchid_extractname_loadtype" data = { "sourcesystem": "xyz", "batchid": "101", "extractname": "abc", "loadtype": "Delta" } filename = '_'.join([data[key] for key in data_file_format.split('_')]) print(filename) 

xyz_101_abc_Delta

Comments

0

.join would be the best answer in this scenario (the answer by bitto). But for the future some good methods are:

>>> a = 1 >>> b = 2 >>> c = "three" >>> "%d and %d then %s" % (a, b, c) 1 and 2 then three >>> "{} and {} then {}".format(a, b, c) 1 and 2 then three >>> f"{a} and {b} then {c}" 1 and 2 then three 

Comments

0

Or you can go basic and go ahead like,

data_file_format = datasourcesystem + "_" + batchid + "_" + extractname + "_" + loadtype 

The previous answer is not far off too. It just forgot the underscores

1 Comment

I want this to be dynamically generated.. as my file format vary from one file to other
-1

you can concat strings in python with +

data_file_format = sourcesystem + "_" + batchid + "_" + extractname + "_" + loadtype 

this should give you "xyz_101_abc_Delta"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.