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
tedd
V2EX  ›  Python

Python [2] 创建中文文件名的问题

  •  
  •   tedd · 2013-08-21 15:54:21 +08:00 · 4896 次点击
    这是一个创建于 3918 天前的主题,其中的信息可能已经有所发展或是发生改变。
    想创建一个中文名的文件,在网上搜了半天,搜出三个方案,都失败了...只有来求助了...

    >>> n = u'文件'
    >>> print n
    文件

    >>> fp = u'c:\\{}.txt'.format(n)
    >>> print fp
    c:\文件.txt

    尝试1:
    >>> f = open(fp, 'w')
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    IOError: [Errno 13] Permission denied: u'c:\\\u6587\u4ef6.txt'

    尝试2:
    >>> f = open(unicode(fp, 'utf-8'), 'w')
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: decoding Unicode is not supported

    尝试3:
    >>> import os.path
    >>> fp2 = os.path.normcase(u'c:/文件.txt')
    >>> f = open(fp2, 'w')
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    IOError: [Errno 13] Permission denied: u'c:\\\u6587\u4ef6.txt'
    8 条回复    1970-01-01 08:00:00 +08:00
    clouder
        1
    clouder  
       2013-08-21 16:03:27 +08:00
    是不是编码问题,加上 #-*- coding: utf-8 -*- 试试
    for4
        2
    for4  
       2013-08-21 16:09:51 +08:00 via Android
    这不是权限问题吗?
    nervouna
        3
    nervouna  
       2013-08-21 16:23:50 +08:00
    permission
    英 [pəˈmɪʃn] 美 [pɚˈmɪʃən]
    n.允许; 批准,正式认可,认可

    denied
    英 [dɪ'naɪəd] 美 [dɪ'naɪəd]
    adj.拒签
    v.拒绝( deny的过去式和过去分词 ); 拒绝承认; 拒绝…占有; 否认知情
    123123
        4
    123123  
       2013-08-21 16:24:33 +08:00
    先把 Permission denied 搞定
    tedd
        5
    tedd  
    OP
       2013-08-21 16:30:15 +08:00
    真的不是权限的问题啊,我已更改文件存放的地方确保能够写入了,还是编码的问题
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 1: ordinal not in range(128)
    banbanchs
        6
    banbanchs  
       2013-08-21 16:49:20 +08:00
    @tedd 编码问题的话应该是这样?
    In [14]: type(fp)
    Out[14]: unicode

    In [15]: type(fp.encode('utf-8'))
    Out[15]: str
    Ever
        7
    Ever  
       2013-08-21 16:51:05 +08:00   ❤️ 1
    windows下面fp.encode('gbk')
    tedd
        8
    tedd  
    OP
       2013-08-21 16:55:18 +08:00
    @Ever 貌似可以了哈~感谢Ever
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5788 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 03:47 · PVG 11:47 · LAX 20:47 · JFK 23:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.