0

I am trying to set a path for directory to read all .txt or .csv files inside of it from jupyter notebook on windows. My initial code was:

import pandas as pd
import numpy as np
import matplotlib as plt

import sys
import ntpath

import glob, os 
# creating list of all .txt in folder
path=r'C:\Users\User\Documents\Scripts on ML_DL_AI_PHM\data'

myfile=glob.glob('*.txt')
all_files = glob.glob(os.path.join(path, "*.txt"))

and it works perfectly fine in spyder.

But, jupyter throw an error message on the cell with setting path variable:

File "<ipython-input-40-2bd796a8736c>", line 1
    path = 'C:\Users\User\Documents\Scripts on ML_DL_AI_PHM\data'
          ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Asking for help from experienced jupyter users...

DavidG
  • 24,279
  • 14
  • 89
  • 82
sp2006
  • 59
  • 3
  • Duplicated question. See https://stackoverflow.com/questions/46972225/how-to-open-local-file-on-jupyter – yoonghm Oct 30 '18 at 15:45
  • 1
    it looks like you forgot the `r` in front of your string. Could that be the case? – onno Oct 30 '18 at 15:48

2 Answers2

1

In the code you have

path=r'C:\Users\User\Documents\Scripts on ML_DL_AI_PHM\data'

However, in the error message you have

path = 'C:\Users\User\Documents\Scripts on ML_DL_AI_PHM\data'

They are not the same.

The r before the string changes how the string is interpreted. With the r the backslashes are treated as just backslashes, without the r they are treated as escape characters.

DavidG
  • 24,279
  • 14
  • 89
  • 82
1

You could just use

\\ instead of \
path= 'C:\\Users\\User\\Documents\\Scripts on ML_DL_AI_PHM\\data'