You may open k
and not 'k'
imports = ["import json", "import defaultdict"]
d = {'1': 'print ("This is test file")', '2': 'print ("This is test file")'}
for k, v in d.items():
with open(k + ".py", 'w') as fr:
for imp in imports:
fr.write(imp + "\n")
fr.write(v)
solved How to create a file with filename as key of dictionary