【问题标题】:Why I am getting an error while reading a csv file? [closed]为什么读取 csv 文件时出现错误? [关闭]
【发布时间】:2017-10-31 20:53:24
【问题描述】:

我正在尝试打开一个 csv 文件,以便将我的彩票号码(从 1 到 54 的六个随机生成的整数)与 1992 年到 2017 年的先前中奖号码进行比较,这是 csv 文件包含的内容。

import random

import csv

six_random_int =[random.randint(1,54),random.randint(1,54),random.randint(1,54),random.randint(1,54),random.randint(1,54),random.randint(1,54)]

print('Your lotto ticket is ',six_random_int)

with open('lottotexas.csv','r') as f:  #This is where the error is occurring
    reader = csv.reader(f)
    for row in reader:
        print(row)

我不断收到错误:

with open('lottotexas.csv','r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'lottotexas.csv'. 

我已经在我的计算机上下载了 csv 文件,但我不知道从那里去哪里,以便我的 python 程序可以找到 csv 文件。

【问题讨论】:

  • python 会尝试从当前工作目录打开文件,你必须提供文件的完整路径
  • 换句话说,它可能会在您的脚本所在的同一目录中查找 CSV。如果您的 python 脚本不在该文件夹中,则将文件放在“下载”中将无济于事.如果它们位于不同的文件夹中,您需要提供文件的绝对路径或相对路径。
  • 对于任何错误,您最好在问这里之前谷歌它。

标签: python csv pycharm


【解决方案1】:

error 中可以清楚地看出你得到了:

with open('lottotexas.csv','r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'lottotexas.csv'. 

Python 找不到文件'lottotexas.csv'

Python 将尝试open 文件的方式是在.py file 中查找filename 的当前directory - 除非您已给出完整的file path。如果您将完整的path 提供给file,则Python 将从该位置打开file

尽管如此,按照您编写此程序的方式,Python 试图在与 Python file 相同的 directory 中找到一个名为 lottotexas.csvfile - 并且没有命名为 file ! - 因此errorFileNotFoundError

【讨论】:

  • 谢谢!现在我将 python 文件和 csv 文件放在同一个目录中,我可以读取 csv 文件
【解决方案2】:

尝试指定文件的完整路径。您必须在放置文件的同一文件夹中执行 python。

【讨论】:

    【解决方案3】:

    请将文件复制并粘贴到您的 python 程序所在的同一路径(文件夹/目录/位置)中。 并再次运行您的程序。 如果问题仍然存在,请检查文件权限。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2015-08-10
      • 2018-05-01
      • 1970-01-01
      • 2021-10-29
      • 2017-01-30
      • 2019-07-31
      相关资源
      最近更新 更多