为什么文件路径在实际上完全有效时却变得无效?

Why does the filepath become invalid when in reality it is completely valid?

import numpy as np
import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import matplotlib.pyplot as plt
%matplotlib inline

filepath = "G:\learning python\page view time series\trum.csv"
df = pd.read_csv(filepath, index_col = "date", parse_dates=True)

以上代码报错如下:

OSError: [Errno 22] Invalid argument: 'G:\learning python\page view time series\trum.csv'

但是如果我将 csv 文件的名称更改为 'laem.csv' 并更新路径,那么代码将完美运行。

import numpy as np
import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import matplotlib.pyplot as plt
%matplotlib inline

filepath = "G:\learning python\page view time series\laem.csv"
df = pd.read_csv(filepath, index_col = "date", parse_dates=True)

为什么会这样?

Python 将字符串中的 \t 解释为制表符的转义码。但是,\l 没有这样的特殊解释,因此它被解释为反斜杠加 l.

为了解决这个问题,我建议使用原始字符串,即在字符串前加上 r:

filepath = r"G:\learning python\page view time series\trum.csv"

或者,您可以转义反斜杠,但这有点乏味:

filepath = "G:\learning python\page view time series\trum.csv"

严格来说,在这种情况下,您真正​​需要转义的唯一一个是 t 之前的那个,但转义一些反斜杠而不是其他反斜杠可能比它值得的麻烦更多(而且可能令人困惑) .

因为 \t 实际上意味着“在此处放置一个制表符 space”,而不是字面上的 \t。 你可以试试看

print("Hello\tWorld") # "Hello   World"

您可以通过使用 \

转义反斜杠本身来避免这种情况
print("Hello\tWorld") # "Hello\tWorld"

或通过在字符串文字前添加 r 来使用原始字符串。

print(r"Hello\tWorld") # "Hello\tWorld"

您可以阅读有关字符串文字的内容 in the docs