1

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?

asked Jun 1, 2017 at 14:12
1
  • 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. Commented Jun 1, 2017 at 14:15

1 Answer 1

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')
answered Jun 1, 2017 at 14:15
Sign up to request clarification or add additional context in comments.

4 Comments

Merci for your answer Jean-Francoise Fabre. I tested it and this works perfectly fine. +1, when I get enough reputation.
@ccasimiro9444 you can accept the answer already. That doesn't require any privileges :)
Accepted it, I am new to this :)
oh yeah! :D and +1 for your great answer

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.