0

I'm trying to run a python file through Jupyter Notebook. The first part of this file asks the user to import the data (.txt) file. Running it on a python IDE works well, however I want to make it work in Jupyter Notebook. I tried uploading the data beforehand, as seen in the image below.enter image description here

It still doesn't detect the file nor reads the data. Any ideas on what else to try?

STEMQs
  • 75
  • 1
  • 10

1 Answers1

1

your jupyter has a directory where the notebooks are saved. If the file is not inside the notebook working directory (or a subtree of it) you can't access it, because it not exists. Your path C:\User\Downloads is obvisouly not this directory. Set your download directory to a jupyter directory, or move your text file. Check in jupyter what your working directory is.

Path errors are common in python. Especially if you often have to switch the programming language and then, few weeks later, back to python. I started to make me a helper method that I use in general in every new notebook and python application, to make not path errors. Maybe it helps you with correct working directory paths in the future.

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)

And then all further paths relative to youur so set working directory (to make sure that your code also runs on other systems thans yours. Also use os.sep instead of \ as path seperator.)

best greetings

ScienceLover
  • 43
  • 1
  • 6