Search code examples
pythonfilefwrite

How do I write to a file with spaces and special characters in file name?


I'm trying to write to a file called

data/STO: INVE-B-TIME_SERIES_DAILY_ADJUSTED-1.csv

using the following python code on windows

overwrite = "w"  # or write new

f = open(OutputPath(copyNr), overwrite)
f.write(response.content.decode('utf-8'))
f.close()

print(f"Wrote to file: {OutputPath(copyNr)}")

The output in the console is correct, but the file written to results in only data/STO so the path seems to be clipped. I've tried to escape the characters using the method from this SO answer but that gave me an invalid_argument exception for the following filename:

data/STO\\:\\ INVE-B-TIME_SERIES_DAILY_ADJUSTED-1.csv

I get the same error when I remove the space and it still seems to clip at :. How do I include such characters in a filename?


Solution

  • You can't. Colons are only allowed on the volumeseperator - anywhere else there are illegal.

    Allowed:

    d:/somedir/somefile.txt
    

    Illegal:

    ./some:dir/somefile.txt
    

    and as seperators you can either use '\\' or '/' - both should be understood.

    This is not a python limitation but a operating system limitation.

    See f.e. What characters are forbidden in Windows and Linux directory names?