Python Forum
needed str around a file pathname to open it - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: needed str around a file pathname to open it (/thread-24406.html)



needed str around a file pathname to open it - adetheheat - Feb-12-2020

I obtained a file pathname ending with .lst in the root dir like this:

for file_path in Path(args.path).glob('**/*.lst'):
and I wanted to open the file file_path but needed str(file_path) to do so:
for codeline in open(str(file_path)):


why did I need the 'str' call ? I thought file_path was a string anyway ?
Is there a way of doing this without the 'str' call as it seems strange I needed it ?
Thanks


RE: needed str around a file pathname to open it - DeaD_EyE - Feb-12-2020

Older Python versions are not everywhere compatible with Path objects. What you see is just the str representation, but it is not a str object. Never versions of Python can handle Path objects in stdlib and builtins. Instead you could also use the Method open of the Path object.

with Path("file.ext").open() as fd:
     for line in fd:
         ...
Tje Path object has also the methods read_text() and read_bytes().