【问题标题】:How to run py file that uses txt file in Jupyter Notebook如何在 Jupyter Notebook 中运行使用 txt 文件的 py 文件
【发布时间】:2021-10-15 05:26:17
【问题描述】:
我正在尝试通过 Jupyter Notebook 运行 python 文件。该文件的第一部分要求用户导入数据 (.txt) 文件。在 python IDE 上运行它效果很好,但是我想让它在 Jupyter Notebook 中运行。我尝试预先上传数据,如下图所示。
它仍然没有检测到文件也没有读取数据。有什么想法可以尝试吗?
【问题讨论】:
标签:
python
python-3.x
import
jupyter-notebook
【解决方案1】:
您的 jupyter 有一个保存笔记本的目录。如果文件不在笔记本工作目录(或其子树)中,则无法访问它,因为它不存在。您的路径 C:\User\Downloads 显然不是这个目录。将您的下载目录设置为 jupyter 目录,或移动您的文本文件。在 jupyter 中检查你的工作目录是什么。
路径错误在 python 中很常见。特别是如果您经常不得不切换编程语言,然后在几周后又回到 python。我开始让我成为一个辅助方法,我通常在每个新的笔记本和 python 应用程序中使用它,以免出现路径错误。也许它可以在将来帮助您正确的工作目录路径。
import os
import sys
from pathlib import Path
def SetWorkingDir(abs_working_dir_path):
Debug = True
try:
if Debug:
print(f"[SetWorkingDir] Initial working directory: {os.getcwd()}", flush=True)
RootDir = False
if RootDir:
root_dir = os.path.dirname(os.path.realpath(__file__))
if Debug:
print(f"[SetWorkingDir] Local dir: {root_dir}", flush=True)
if (os.getcwd() != abs_working_dir_path):
os.chdir(abs_working_dir_path)
if Debug:
print(f"[SetWorkingDir] Working directory changed to: {os.getcwd()}", flush=True)
else:
if Debug:
print(f"[SetWorkingDir] Working directory unchanged at: {os.getcwd()}", flush=True)
return os.getcwd()
except Exception as ex:
print(f"\n[SetWorkingDir] Exception:"
f"\n{'Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(ex).__name__, ex}\n", flush=True)
然后是相对于您的所有其他路径,因此设置工作目录(以确保您的代码也可以在您的系统之外的其他系统上运行。同时使用 os.sep 而不是 \ 作为路径分隔符。)
最好的问候