Search code examples
pythonfilecmdpathrelative-path

Running Python in CMD - Cannot create file


Im trying to call a python file through a shell (CMD), but I get some issues.

When I run my .py file either by double clicking the .py file or through the Python IDLE editor, it runs just fine, and creates files just as it should.

But when I run it through command line, it runs through the file, but does not "open" / create a file.

I assume / think it might have something to do with the relative file path, but I'm not sure

The script is:

from __future__ import print_function
import sys
import os
import ctypes    
#-----File-Handling-------------------  

#Remove previous output file
if os.path.exists("Temp_py_out.txt"):
  os.remove("Temp_py_out.txt")

#create file:
tempfile = open("Temp_py_out.txt", "w+")
tempfile.write("0\nNo errors\nPar1\nPar2\nPar3\nPar4\nPar5\nPar6\n")

tempfile.close()
print("File OK")

EDIT: I can see it creates an file, but instead of in the folder where the .py is located, it creates it in my "C:\Users\meg" folder, which is the default folder my CMD is in when I open CMD.

How do I get python to force place it in the same folder as where the file is located?


Solution

  • Using this command to run

    C:\Users\meg>python "C:\Users\meg\Desktop\PYTEST\test.py"
    

    will use your current working directory C:\Users\meg, instead of the location of your Python file. Check that folder to see if there are files you're expecting.