pathlib PurePosixPath

Tim Golden mail at timgolden.me.uk
Tue Oct 10 05:56:58 EDT 2017


On 2017-10-10 10:28, Chris Angelico wrote:
> On Tue, Oct 10, 2017 at 8:22 PM, Tim Golden <mail at timgolden.me.uk> 
> wrote:
>> On 2017-10-10 08:29, Chris Angelico wrote:
>>> 
>>> On Tue, Oct 10, 2017 at 6:21 PM, Sayth Renshaw 
>>> <flebber.crue at gmail.com>
>>> wrote:
>>>> 
>>>> Hi
>>>> 
>>>> How do I create a valid file name and directory with pathlib?
>>>> 
>>>> When I create it using PurePosixPath I end up with an OSError due to 
>>>> an
>>>> obvously invlaid path being created.
>>> 
>>> 
>>> You're on Windows. The rules for POSIX paths don't apply to your file
>>> system, and...
>>> 
>>>> OSError: [Errno 22] Invalid argument:
>>>> 'C:\\Users\\Sayth\\Projects\\results/Warwick 
>>>> Farm2017-09-06T00:00:00.json'
>>> 
>>> 
>>> ... the colon is invalid on Windows file systems. You'll have to
>>> replace those with something else.
>> 
>> 
>> I haven't followed closely, so this may well not be an issue here, but 
>> the
>> colon is valid on a Windows file system; it introduces an alternate 
>> data
>> stream:
>> 
>> https://msdn.microsoft.com/en-us/library/windows/desktop/aa364404(v=vs.85).aspx
>> 
>> So this is perfectly valid on Windows:
>> 
>> with open("temp.txt:abc", "w") as f:
>>     f.write("abc")
> 
> Have you tested that?

Yes. I ran it before posting.

> My understanding of the document you linked to
> is that the colon still has special meaning, and thus you can't use it
> in arbitrary file names.

In fact its presence in that filename creates a (usually hidden) data 
stream piggybacked onto that file which has the name "abc" into which 
the data is written.

So, following on, the follow works:

assert open("temp.txt:abc").read() == "abc"

TJG



More information about the Python-list mailing list