Python Forum
needed str around a file pathname to open it
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
needed str around a file pathname to open it
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 ?
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().
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die:
All humans together. We don't need politicians!

Possibly Related Threads…
Thread Author Replies Views Last Post
  Error on open of file created with tempfile.TemporaryDirectory() Brian177 4 224 Apr-05-2021, 07:12 PM
Last Post: Brian177
  I can't open a python file :( Oshadha 2 301 Mar-28-2021, 11:00 PM
Last Post: pythonprogrammer1101935
  How to open MIDI-file and get events in a list? philipbergwerf 6 946 Mar-25-2021, 08:23 PM
Last Post: philipbergwerf
  Python win32com.client: What are the syntax to open exe file & activate its window? JaneTan 0 525 Oct-14-2020, 09:09 AM
Last Post: JaneTan
  open(file, 'rb') raises UnicodeDecodeError binnybit 1 419 Sep-28-2020, 06:55 AM
Last Post: Gribouillis
  open vlc movie file on raspberrypi Nickd12 4 537 Sep-22-2020, 10:57 PM
Last Post: Nickd12
  What is meant by "truncates the file" RE MysticLord 5 767 Sep-01-2020, 08:36 PM
Last Post: bowlofred
  Can't open/read txt file in C extension for Python Rad226 8 1,205 Jun-26-2020, 04:08 PM
Last Post: Rad226
  Can't open file rdgbl 1 641 May-26-2020, 07:51 PM
Last Post: bowlofred
  How do I open a file and the plot it? HelixFossil 1 553 Apr-17-2020, 11:00 PM
Last Post: thirteendec

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020