V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
durden
V2EX  ›  Python

为写入的文件创建不同的文件名

  •  
  •   durden · 2012-09-12 22:32:00 +08:00 · 2850 次点击
    这是一个创建于 4236 天前的主题,其中的信息可能已经有所发展或是发生改变。
    var_list = ['one','two','three']

    for i in var_list:
    f = open('var_list[i].htm', 'w')
    html = '''
    <html>
    <head><title></title></head>
    <body>
    <strong><font color=red>Hello World!</font></strong>
    </body>
    </html>
    '''
    f.write(html)
    f.close()


    我想创建三个one.htm, two.htm, three.htm文件出来,但‘var_list[i].htm’明显不是正确的写法,搜了半天也找不到方案特来求教,谢谢先~
    4 条回复    1970-01-01 08:00:00 +08:00
    Brutal
        1
    Brutal  
       2012-09-12 22:33:00 +08:00   ❤️ 1
    f = open('%s.htm' % (i,), 'w')
    yuelang85
        2
    yuelang85  
       2012-09-12 22:33:12 +08:00
    "%s.html"%var_list[i]
    yuelang85
        3
    yuelang85  
       2012-09-12 22:34:02 +08:00
    哦,一楼是对的,没看到楼主用的是for...in
    durden
        4
    durden  
    OP
       2012-09-12 22:43:55 +08:00
    @Brutal 感谢你!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2981 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:03 · PVG 23:03 · LAX 08:03 · JFK 11:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.