I was evaluating PyCharm with one of my script and went into a problem directly at first line. In my script I do this:
filename = './trial/{0}'.format(sys.argv[0].split('\\')[-1].replace(".py",""))
Splitting with "\\"
worked everytime on the command prompt (I'm working on Windows)
If I run/debug in PyCharm the "\\"
split doesn't work, I've seen the file is launched by the interpreter as:
"C:\Python26\python.exe C:/Users/nboldri/Desktop/..."
so it gets as separator "/"
and split function doesn't work with "\\"
Is there a way in PyCharm to pass the filepath to the interpreter in the windows format with backslash? I've searched but couldn't find anything in settings or internet.
You're getting the file name and removing the extension.
Use os.path.splitext, which returns the file path and its extension, and os.path.basename to get the filename:
import os
import sys
filename, extension = os.path.splitext(os.path.basename(sys.argv[0]))
trialname = './trial/{0}'.format(filename)
If this is used in lots of places in your code, replace it with a function:
def filename_with_no_extension(filepath):
from os.path import splitext, basename
return splitext(basename(filepath))
Then:
import sys
trialname = './trial/{0}'.format(filename_with_no_extension(sys.argv[0])