Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

Tags:

python

I am new to programming, this is actually my first work assignment with coding. my code below is throwing an error:

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect.

I'm not able to find where the issue is.

import os

folders = ["pdcom1", "pdcom1reg", "pdcomopen"]


for folder in folders:
    path = r'"C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1"'
    for file in os.listdir(path):
        print file
like image 515
AlliDeacon Avatar asked Nov 09 '15 21:11

AlliDeacon


3 Answers

As it solved the problem, I put it as an answer.

Don't use single and double quotes, especially when you define a raw string with r in front of it.

The correct call is then

path = r"C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1"

or

path = r'C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1'
like image 65
jkalden Avatar answered Nov 08 '22 18:11

jkalden


I had a related issue working within Spyder, but the problem seems to be the relationship between the escape character ( "\") and the "\" in the path name Here's my illustration and solution (note single \ vs double \\ ):

path =   'C:\Users\myUserName\project\subfolder'
path   # 'C:\\Users\\myUserName\\project\subfolder'
os.listdir(path)              # gives windows error
path =   'C:\\Users\\myUserName\\project\\subfolder'
os.listdir(path)              # gives expected behavior
like image 22
Kevin Burns Avatar answered Nov 08 '22 20:11

Kevin Burns


This is kind of an old question but I wanted to mentioned here the pathlib library in Python3.

If you write:

from pathlib import Path
path: str = 'C:\\Users\\myUserName\\project\\subfolder'
osDir = Path(path)

or

path: str = "C:\\Users\\myUserName\\project\\subfolder"
osDir = Path(path)

osDir will be the same result.

Also if you write it as:

path: str = "subfolder"
osDir = Path(path)
absolutePath: str = str(Path.absolute(osDir))

you will get back the absolute directory as

'C:\\Users\\myUserName\\project\\subfolder'

You can check more for the pathlib library here.

like image 3
bad_locality Avatar answered Nov 08 '22 19:11

bad_locality