【问题标题】:How can python return the filename currently being processed under Windowspython如何返回windows下当前正在处理的文件名
【发布时间】:2011-07-13 16:36:58
【问题描述】:

我是 python 新手,只想做一个简单的改变。我们正在 Windows 7 下通过 mako 生成模板文件,我想将输出文件开头的 cmets 更改为:

/////////////////////////////////////////////////////////////////
// This file is automatically generated by Mako
/////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////
// This file is automatically generated by Mako from ${filename}
/////////////////////////////////////////////////////////////////

那么,插入正在处理的实际文件名的真正代码是什么?

【问题讨论】:

    标签: python mako


    【解决方案1】:
    import os
    
    filename = os.path.basename(__file__)
    print ('this is generated by ' + filename)
    

    【讨论】:

    • 编辑了答案。这只会给你文件名,而不是文件路径。
    【解决方案2】:

    对于python脚本本身的名称,使用__file__

    $ echo "print __file__" > test.py                    
    $ python test.py 
    test.py
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 2013-11-20
      相关资源
      最近更新 更多