Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using pathlib, getting error: TypeError: invalid file: PosixPath('example.txt')

I'm using Python 3's pathlib module, like this:

from pathlib import Path  filename = Path(__file__).parent / "example.txt" contents = open(filename, "r").read() 

But I get this error on some machines:

TypeError: invalid file: PosixPath('example.txt') 

But on my machine it works.

like image 243
Flimm Avatar asked Mar 09 '17 11:03

Flimm


People also ask

What is pathlib PosixPath?

PosixPath() is the child node of Path() and PurePosixPath() , implemented to handle and manipulate non-Windows file system paths. In [*]: pathlib.

Is pathlib in standard library?

Pathlib module in Python provides various classes representing file system paths with semantics appropriate for different operating systems. This module comes under Python's standard utility modules.

What is pathlib import path in Python?

The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.


1 Answers

pathlib integrates seemlessly with open only in Python 3.6 and later. From Python 3.6's release notes:

The built-in open() function has been updated to accept os.PathLike objects, as have all relevant functions in the os and os.path modules, and most other functions and classes in the standard library.

To get it to work in Python 3.5 and Python 3.6, just convert the object to a string:

contents = open(str(filename), "r").read() 
like image 126
Flimm Avatar answered Sep 21 '22 10:09

Flimm