【问题标题】:Why does the filepath become invalid when in reality it is completely valid?为什么文件路径在实际上完全有效时变得无效?
【发布时间】:2021-01-06 14:04:00
【问题描述】:
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)

为什么会这样?

【问题讨论】:

  • 让我们直接阅读。 filepath =r"G:\learning python\page view time series\laem.csv"
  • @wwnda。不错的收获!

标签: python pandas csv path filepath


【解决方案1】:

因为\t 实际上的意思是“在这里放一个制表符”,而不是简单的\t。 您可以通过尝试看到这一点

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

您可以通过使用 \\ 转义反斜杠本身来避免这种情况

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

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

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

您可以阅读有关字符串文字 in the docs.

【讨论】:

    【解决方案2】:

    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 之前的那个,但是转义一些反斜杠而不是其他反斜杠可能比它的价值更麻烦(也可能令人困惑)。

    【讨论】:

      猜你喜欢
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 2014-03-12
      • 2016-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多