【问题标题】:Python shell not finding the file that is in the same folder (CSV)Python shell 找不到位于同一文件夹中的文件 (CSV)
【发布时间】:2021-03-25 06:04:01
【问题描述】:

我是 python 新手,正在学习使用 CSV 打开/读取文件。 在我的文件夹中,我有一个 fruit.txt 文本文件(记事本),我正在尝试使用以下代码在 python shell 上打开它:

import csv

inFile = open("fruit.txt", "r")

我得到这个错误:

File "<pyshell#11>", line 1, in <module>
inFile = open("fruit.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'fruit.txt'

我将文本文件和程序放在同一个文件夹中;不知道是什么问题。

Here is the screenshot of my folder

谢谢:)

【问题讨论】:

  • 你是如何执行你的脚本的?
  • 我只是在 IDLE (python 3.8 32-bit) 上点击进入

标签: python


【解决方案1】:

相对文件路径是相对于您当前的工作目录(您的终端打开的目录),而不是正在执行的文件。您可以使用

检查您的工作目录
import os
print(os.getcwd())

尝试将终端的工作目录移动到脚本目录,然后运行程序。

【讨论】:

  • 我将包含水果文本的文件夹 python 脚本移动到我的工作目录。然后我使用 os.chdir('pythonScripts') 更改目录,我仍然得到这个错误!! Traceback(最近一次调用最后一次):文件“”,第 1 行,在 os.chdir('pythonScripts') FileNotFoundError: [WinError 2] 系统找不到指定的文件:'pythonScripts'
  • @Selina 这个错误是说文件夹pythonScripts 找不到。您可能已经在该文件夹中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 2015-04-25
  • 2021-05-27
  • 2022-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多