【问题标题】:File path with Python and Windows on Jupyter NotebookJupyter Notebook 上 Python 和 Windows 的文件路径
【发布时间】:2018-01-23 12:17:57
【问题描述】:

我无法在 Windows 上的 Jupyter Notebook 上打开文件。

我尝试了 StackOverFlow 上几篇文章中的所有建议(包括这篇非常完整的文章:Windows path in python

我的代码是这个:

today_date = date.today()
path2file = 'D:/Users/XXX123/My_folder/Project/Sub_folder/Relevés/audit/Forms_'+'{:%Y%m%d}'.format(today_date)+'.csv'
print(path2file)
pd.read_csv(os.path.normpath(path2file))

我收到了这个错误信息:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-14-01089ab15706> in <module>()
      4 print(path2file)
      5 
----> 6 pd.read_csv(os.path.normpath(path2file))

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    653                     skip_blank_lines=skip_blank_lines)
    654 
--> 655         return _read(filepath_or_buffer, kwds)
    656 
    657     parser_f.__name__ = name

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
    403 
    404     # Create the parser.
--> 405     parser = TextFileReader(filepath_or_buffer, **kwds)
    406 
    407     if chunksize or iterator:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds)
    762             self.options['has_index_names'] = kwds['has_index_names']
    763 
--> 764         self._make_engine(self.engine)
    765 
    766     def close(self):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in _make_engine(self, engine)
    983     def _make_engine(self, engine='c'):
    984         if engine == 'c':
--> 985             self._engine = CParserWrapper(self.f, **self.options)
    986         else:
    987             if engine == 'python':

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in __init__(self, src, **kwds)
   1603         kwds['allow_leading_cols'] = self.index_col is not False
   1604 
-> 1605         self._reader = parsers.TextReader(src, **kwds)
   1606 
   1607         # XXX

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.__cinit__ (pandas\_libs\parsers.c:4209)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._setup_parser_source (pandas\_libs\parsers.c:8873)()

FileNotFoundError: File b'D:\\Users\\XXX123\\My_folder\\Project\\Sub_folder\\Relev\xc3\xa9s\\audit\\Forms20180123.csv' does not exist

我尝试了几种解决方案:斜杠、反斜杠、双反斜杠、三重反斜杠、双引号或三引号、r'...'、os.path.normpath('...')、...但我仍然不能打开我的文件。

有人有想法吗?

注意:我的文件确实存在...

感谢您的帮助。

【问题讨论】:

  • 提供实际文件路径
  • 上面写着FileNotFoundError。所以问题是访问文件。如果您确定该文件确实存在 - 尝试将 Relevés 重命名为 Releves,然后重试。也许问题在于该字母的编码。还有一点 - Python 区分大小写。
  • 一种快速的调试方法是从路径本身复制文本(右键单击文件>属性>安全选项卡)并进行等效检查path = path2file,其中path是字符串本身。您可以在字符串前面使用r 将其强制为字符串文字,但最好将斜杠替换为反斜杠。如果您不知道自己在做什么,字符串文字可能会产生奇怪的副作用。
  • 另外,只要把它扔出去,就没有必要把你的格式函数放在字符串连接的中间。您可以将这些括号留在那里,将格式移到末尾,并将其保留为一个字符串。像这样:'D:/Users/XXX123/My_folder/Project/Sub_folder/Relevés/audit/Forms_{:%Y%m%d}.csv'.format(today_date)`
  • 显然您正在使用在 parser.c 中实现的 C 扩展,它将 str 路径编码为 UTF-8 字节,然后可能调用低级 C 或 Windows API 来打开这些字节小路。 C 运行时和 Windows API 将字节路径解码为 ANSI。 Windows 的 API 级别不支持 UTF-8。可能是 C 扩展名被混淆了。从 3.6 开始,sys.getfilesystemencoding() 在 Windows 中是 UTF-8。但这仅适用于高级 Python API。内部字节路径被解码为原生 UTF-16LE 编码。

标签: python windows python-3.x jupyter-notebook


【解决方案1】:

确保无需任何额外权限即可访问您的文件所在的文件夹
如果仍然出现错误,只需将工作文件夹更改为桌面,即将项目文件夹移动到桌面并从那里加载。这对我有用,因为 jupyter 的默认启动位置给了我同样的错误。

【讨论】:

    【解决方案2】:

    尝试:

    import datetime
    import os
    import pandas as pd
    import sys
    
    today_date = datetime.date.today()
    path2file = r'D:/Users/XXX123/My_folder/Project/Sub_folder/Relevés/audit/Forms_'+'{:%Y%m%d}'.format(today_date)+'.csv'
    # check that the file path exists
    if not os.path.exists(path2file):
        print('{} not found'.format(path2file))
        sys.exit()
    pd.read_csv(os.path.normpath(path2file))
    

    os.path.exists 检查您是否拥有有效的文件路径。

    将“r”符号放在文件路径之前可确保解释器不会更改字符串,认为其中一个反斜杠表示字符代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      相关资源
      最近更新 更多