dekuShrub
dekuShrub

Reputation: 486

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?

Upvotes: 0

Views: 1161

Answers (2)

wasif
wasif

Reputation: 15498

Windows API will not allow colon in filename, it is reserved for drive letter, use a different sign.

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51683

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?

Upvotes: 1

Related Questions