-1

My code throws an exception

path='E:\programming_section\data_science_and_ml\kist\six_sem_project\alImdb '
positiveFiles = [x for x in os.listdir(path+"train\pos\") if x.endswith(".txt")]
negativeFiles = [x for x in os.listdir(path+"train\neg\") if x.endswith(".txt")]
testFiles = [x for x in os.listdir(path+"test\") if x.endswith(".txt")]

The exception:

    SyntaxError: **EOL while scanning string literal

How can I resolve this?

kendriu
  • 565
  • 3
  • 21
dipu sah
  • 1
  • 1
  • You cannot end a string with a single trailing slash, e.g. `"train\pos\"`. [See here](https://stackoverflow.com/questions/2870730/python-raw-strings-and-trailing-backslash) – Cory Kramer Jan 06 '20 at 15:48

1 Answers1

-1

Always remember that slashes behave differently from most other symbols in strings. Slashes in python usually are for making special characters. With that said always remember that you cannot end python string with \ slashes, what you want to do is either escape it or make it a raw string since it is a path. For a raw string you should have something like this

path='E:\programming_section\data_science_and_ml\kist\six_sem_project\alImdb '
positiveFiles = [x for x in os.listdir(path+r"train\pos\") if x.endswith(".txt")]
negativeFiles = [x for x in os.listdir(path+r"train\neg\") if x.endswith(".txt")]
testFiles = [x for x in os.listdir(path+r"test\") if x.endswith(".txt")]

But if you decide to go with escaping the slashes then

path='E:\programming_section\data_science_and_ml\kist\six_sem_project\alImdb '
positiveFiles = [x for x in os.listdir(path + "train\pos" + "\\") if x.endswith(".txt")]
negativeFiles = [x for x in os.listdir(path + "train\neg" + "\\") if x.endswith(".txt")]
testFiles = [x for x in os.listdir(path + "test" + "\\") if x.endswith(".txt")]

You could also consider using the os.path.join

path='E:\programming_section\data_science_and_ml\kist\six_sem_project\alImdb '
positiveFiles = [x for x in os.listdir(os.path.join(path + "train\pos") if x.endswith(".txt")]
negativeFiles = [x for x in os.listdir(os.path.join(path + "train\neg")) if x.endswith(".txt")]
testFiles = [x for x in os.listdir(os.path.join(path + "test")) if x.endswith(".txt")]

Personally i would recommend the raw string option

maestro.inc
  • 796
  • 1
  • 6
  • 13
  • OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'E:\\programming_section\\data_science_and_ml\\kist\\six_sem_project\x07lImdb train\\pos\\' using this follwing error occured – dipu sah Jan 07 '20 at 08:08
  • Which is why i recommended using the raw string version. You could also consider using the `os.path.join()` function – maestro.inc Jan 08 '20 at 08:20