Reputation: 301
I'm creating a very basic python program that allows a user to enter a command that is then ran as code.
For example I have imported a file called textScripts.py: within that file there is a function called createFile()
. When the user enters textScripts.createFile()
it is passed into exec()
. It runs without error and exits the program but the file isn't created!
I know the createFile()
function works because if I put textScripts.createFile()
in the code it creates a file.
Here is the relevant snippet of code:
commandList=[]
while(commandRun):
count = 0
commandList.append(input(">>>"))
exec(commandList[count])
print(commandList[count])
count += 1
here is a screenshot of the code being run:
>>> textScripts.createFile()
>>>
here is a screenshot of the folder:
__pyCache__
textScripts.py
CLIFile.py
there should be a file in this folder
here is the function createFile()
:
def createFile(
destination = os.path.dirname(__file__),
text = "Sick With the Python\n"
):
''' createFile(destination, text)
This script creates a text file at the
Specified location with a name based on date
'''
date = t.localtime(t.time())
name = "%d_%d_%d.txt" %(date[1], date[2], date[0])
if not(os.path.isfile(destination + name)):
f = open(destination + name, "w")
f.write( text )
f.close
else:
print("file already exists")
I apologize in advance if this is an obvious questions; I'm new to python and have been looking for hours for an answer as to why this happens.
Upvotes: 2
Views: 60
Reputation: 1291
You save file to wrong folder (you can insert "print(destination + name)" in your function)
You need to replace this:
destination + name
to this:
os.path.join(destination, name)
PS:
For example:
with open('file.txt', 'w') as f:
f.write('line')
Upvotes: 1