【问题标题】:Python error "FileNotFoundError: [Errno 2] File b Usuarios.csv' does not exist: b Usuarios.csv'"Python 错误“FileNotFoundError:[Errno 2] 文件 b Usuarios.csv' 不存在:b Usuarios.csv'”
【发布时间】:2020-06-05 16:29:10
【问题描述】:

我正在使用 pandas 读取 csv 文件,当我在 Spyder 上运行它时,代码运行得很好,但是,当我尝试在 anaconda 提示符下运行它甚至双击 .py 文件时,它没有运行.在 anaconda 提示符下,我收到“FileNotFoundError: [Errno 2] File b Usuarios.csv' 不存在:b Usuarios.csv'”错误,即使该文件确实存在并且它与 .py 文件位于同一目录中。我正在使用此代码:

import pandas 
import csv

csv_reader = pandas.read_csv("D:\\clovi\\Projetos\\Python\\Usuarios.csv",encoding='utf-8')

j=0
y = csv_reader.iloc[-1].values[0]

while True:
    i=0
    x = csv_reader.iloc[j].values
    usuario = x[i]
    i+=1
    pase = x[i]
    j+=1
    if usuario == y:
        edistribucion(usuario,pase)
        break
    else:
        edistribucion(usuario,pase)

注意:为了读取文件,我也尝试过

import pandas as pd
import csv

csv_reader = pd.read_csv("Usuarios.csv")

.
.
.

正如我所说,当我在 Spyder 上运行时它运行良好,但在其他任何地方都无法运行。我在代码上做错了什么?

【问题讨论】:

    标签: python pandas file csv spyder


    【解决方案1】:

    输入 Spyder CLI:

    import os
    print(os.getcwd())
    

    转到 Anaconda Prompt 中的结果目录:

    cd path\from\Spyder\print
    

    现在启动您的脚本。您可以将其复制到目录或通过路径调用。

    【讨论】:

    • 我也尝试过这样做,但我得到的路径与我在 Anaconda Prompt 中输入的路径相同。我还注意到,我在读取 .csv 文件的所有代码中都遇到了同样的错误,但同样,它们在 Spyder 甚至 Visual Studio 上运行良好
    【解决方案2】:

    可能是 Anaconda 提示没有权限访问 CSV 文件所在的目录。在这种情况下,您可以修改脚本以接受命令行参数,如果没有,则默认为您已有的路径,如下所示:

    import sys
    import os
    import pandas 
    import csv
    
    # If there is a command-line argument, and the argument is a valid file, this matches
    if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
        csv_path = sys.argv[1]
    else:
        csv_path = r'D:\clovi\Projetos\Python\Usuarios.csv'
    
    csv_reader = pandas.read_csv(csv_path,encoding='utf-8')
    
    j=0
    y = csv_reader.iloc[-1].values[0]
    
    while True:
        i=0
        x = csv_reader.iloc[j].values
        usuario = x[i]
        i+=1
        pase = x[i]
        j+=1
        if usuario == y:
            edistribucion(usuario,pase)
            break
        else:
            edistribucion(usuario,pase)
    

    您可以在不破坏代码的情况下动态更改 CSV,因此在命令行中:

    # This tries to process the hard-coded CSV
    python clovis_magno.py
    
    # While this processes top_secret_data.csv in your Desktop
    python clovis_magno.py "C:\Users\Clovis Magno\Desktop\top_secret_data.csv"
    

    【讨论】:

    • 成功了,谢谢!!现在当我在 Anaconda Prompt 中执行它时它会运行,但是通过双击 .py 文件执行它时我仍然遇到一些问题,不过我可以稍后解决它
    • 我也可以帮你解决这个问题。
    • 双击打开脚本的问题是你需要在脚本的顶部添加一个shebang,而AFAIK你不能传递命令行参数,比如你的CSV文件的路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    相关资源
    最近更新 更多