我正在使用Spyder IDE,Python 3.5版本,它是Anaconda发行版的一部分。以下是代码的前几行:
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 20 16:22:40 2016
@author: pavan
This program reads csv file from the given directory .
The input directory for this is : "C:\Users\pavan\Documents\Python Scripts\EOD from Yahoo"
The output file is "comprehensive_trend.xlsx"
"""
import pdb
import pandas as pd
from datetime import date, datetime, timedelta
import os, glob
# Delarations
full_path = os.path.realpath(__file__)
current_directory = os.path.dirname(full_path)
directory = current_directory + "\\EOD from Yahoo\\"
#directory = "C:\\Users\\pavan\Documents\\Python Scripts\\EOD from Yahoo\\"
我曾在Python 2.7上运行这段代码,一切正常。最近我迁移到了Python 3.5,但是当我执行这段代码时,输出如下:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 145-146: truncated \UXXXXXXXX escape
在苦思冥想了一番后,我从注释部分中删除了这行代码:
The input directory for this is : "C:\Users\pavan\Documents\Python Scripts\EOD from Yahoo"
现在程序可以正确运行。
我的疑问:
- 为什么会发生这种情况?
- 在 Python 3.5 中编写注释,避免此类错误的最佳方法是什么?
\U
(如在C:\Users
中)有特殊含义。尝试在注释前直接添加一个"r"来告诉Python不要解释它,例如r""" ... Created on ..."""
。请注意,这不会改变原始字符串的意义。 - Phillip