So, I have been trying to execute a concatenated string in Python 3 and it worked. This function would eventually go into a (while) loop, where the loop counts up to the current month.
def all_installs_to_dataframe(month):
'''Imports csv's from different months to pandas dataframes'''
command = ["dataset = pd.read_csv('/path/file2017", "_overview.csv', sep=',', header=0, encoding='utf-16')"]
return (command[0] + month + command[1])
exec(all_installs_to_dataframe("05"))
However, on my extensive research on Stackoverflow it seems like exec() is not liked (except for trustworthy input). Hence, I would like to know how to do this better? I found that many are fond of dictionaries, I tried this and it would give me a string as well:
dict = {'start': "dataset = pd.read_csv('/path/file2017", 'month': "05", 'end': "_overview.csv', sep=',', header=0, encoding='utf-16')"}
exec(dict['start']+dict['month']+dict['end'])
Which I would have to exec() again.
So, how could I do this without using the exec() statement?
@nico: I initially had this loop over all my files (with datetime library):
month_date = 3
while month_date - 1<date.today().month:
dataset = "dataset_%s" % (month_date)
function = "pd.read_csv('/path/file2017%s_overview.csv', sep=',', header=0, encoding='utf-16')" % (month_date)
dataset = function
month_date += 1
Then I realized that I get a string and it won't work. So I am using the exec() function now. But everywhere I read I shouldn't use it, so how could I circumvent the exec() function in this loop?
-
Is there a reason you're not just sending the csv path directly? Are the commands diverse enough that this will not work? I'm trying to better understand what you want to do.nico– nico2017年06月01日 14:15:15 +00:00Commented Jun 1, 2017 at 14:15
1 Answer 1
Why not executing the command in the function and compose the filename using str.format instead of using exec ?
def all_installs_to_dataframe(month):
'''Imports csv's from different months to pandas dataframes'''
dataset = pd.read_csv('/path/file2017{}_overview.csv'.format(month), sep=',', header=0, encoding='utf-16')