简体   繁体   English

PyCharm文件路径分隔符

[英]PyCharm file path separator

I was evaluating PyCharm with one of my script and went into a problem directly at first line. 我当时正在用我的一个脚本评估PyCharm,直接在第一行遇到了问题。 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) 每次都在命令提示符下使用"\\\\"拆分(我在Windows上工作)

If I run/debug in PyCharm the "\\\\" split doesn't work, I've seen the file is launched by the interpreter as: 如果我在PyCharm中运行/调试,则"\\\\"拆分不起作用,我已经看到文件由解释器启动为:

"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? PyCharm中是否有一种方法可以使用反斜杠将文件路径传递给Windows格式的解释器? I've searched but couldn't find anything in settings or internet. 我已经搜索过,但在设置或互联网中找不到任何内容。

Thank you! 谢谢!

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: 使用os.path.splitext返回文件路径及其扩展名,并使用os.path.basename获取文件名:

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM