0

I think/hope this a an easy question that I just can't find the answer to - how do I create a directory where the title contains a colon? I'm scraping data from a website with variables for section and year, and creates a directory:

if 'C:/Path/Data/%s' % stat:
    directory = 'C:/Path/Data/%s' % stat                
else:                
    directory = 'C:/Path/Data/%s' % stat.replace('/', ' ')
if not os.path.exists(directory):
    try:
        os.makedirs(directory)
    except OSError as e:
        if not e.errno != errno.EEXIST:
            raise

I have some error handling in there based on what's coming back. I had to bring in errno to skip the section that was erring. I want to bring in that data however - and I believe the issue is the title of the section, and thus the directory, contains a : in a directory like:

/Year: some_data/

I receive this error:

OSError: [Errno 22] Invalid argument:
Failed with OSError

My question is - how do I create or handle the creation of a directory with a : in the title? I'm just skipping over it for now.

I apologize if this is a duplicate but I couldn't find anything specifically. I'm running python 3.6 in Jupyter Notebook on Windows 10. Thank you.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Hatt
  • 689
  • 4
  • 9
  • 23
  • Is `C:Path` supposed to be `C:/Path`? – Mad Physicist Jun 21 '18 at 15:37
  • Also, fix your indentation. Python is space-sensitive, so what you have posted is not valid Python code. – Mad Physicist Jun 21 '18 at 15:37
  • @MadPhysicist - correct, I was just masking the actual directory name, forgot the '/'. Also correct - pasting the code sent the first line over - the indentation is aligned in the actual script. – Hatt Jun 21 '18 at 15:39
  • You don't. `:` marks devices in DOS, Windows, and several other systems and is a path separator in MacOS. See e.g. [MSDN](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx) and [What characters are forbidden in Windows and Linux directory names?](https://stackoverflow.com/questions/1976007/what-characters-are-forbidden-in-windows-and-linux-directory-names) – Yann Vernier Jun 21 '18 at 15:41
  • 1
    The `if` will never be `False`: A non-empty string is always `True`. – Mad Physicist Jun 21 '18 at 15:41
  • Gotcha - so it sounds like I can't handle the special characters in the path title - rather I need to replace the character immediately after pulling it down and before creating a directory. – Hatt Jun 21 '18 at 15:56

0 Answers0