2016-12-13 76 views
0
try: 
     print(filePath) 
     my_file = Path(filePath) 
    except ValueError: 
     print ValueError 

试图运行该代码使用路径(文件)不断抛出的错误:不能没有抛出异常

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 26: ordinal not in range(128)

吹它的值是: Kellyanne Conway: Giuliani’s Withdrawal From Consideration A ‘Mutual Decision’ | MTP Daily | MSNBC.opus

我试着用ascii和unicode编码这个字符串,但它没有奏效。如何检查文件是否正确存在,谢谢。

+0

什么是'Path'? – TigerhawkT3

+0

'from pathlib import Path' – Antoine

+0

Python 2或Python 3?它很重要。请参阅http://stackoverflow.com/questions/33938079/why-python2-and-python3-treat-same-windows-directory-differently和https://pypi.python.org/pypi/pathlib/(搜索“ASCII “) –

回答

0

使用os.path代替pathlib。

import os 

print os.path.exists(filePath) 
print os.path.isfile(filePath) 

Python 3之前的pathlib不能很好地处理非ASCII字符。请参阅:

Why Python2 and Python3 treat same windows directory differently?

https://pypi.python.org/pypi/pathlib/(搜索 “ASCII”)

+0

工程就像一个魅力,谢谢。我出来upvotes但会投票,当我再次得到一些,thx – Antoine

+0

我试图使用Python 3,但遇到了一些SSL错误 – Antoine