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
#1
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
Reply
#2
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().
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Open/save file on Android frohr 0 317 Jan-24-2024, 06:28 PM
Last Post: frohr
  file open "file not found error" shanoger 8 1,089 Dec-14-2023, 08:03 AM
Last Post: shanoger
  How can i combine these two functions so i only open the file once? cubangt 4 853 Aug-14-2023, 05:04 PM
Last Post: snippsat
  I cannot able open a file in python ? ted 5 3,306 Feb-11-2023, 02:38 AM
Last Post: ted
  testing an open file Skaperen 7 1,375 Dec-20-2022, 02:19 AM
Last Post: Skaperen
  Code Assistance needed in saving the file MithunT 0 812 Oct-09-2022, 03:50 PM
Last Post: MithunT
  I get an FileNotFouerror while try to open(file,"rt"). My goal is to replace str decoded 1 1,400 May-06-2022, 01:44 PM
Last Post: Larz60+
  Dynamic File Name to a shared folder with open command in python sjcsvatt 9 6,026 Jan-07-2022, 04:55 PM
Last Post: bowlofred
  Open an excel file Newbie1114 1 2,339 Jun-16-2021, 09:11 PM
Last Post: Gribouillis
  How to open MIDI-file and get events in a list? philipbergwerf 7 4,970 May-29-2021, 08:24 AM
Last Post: j.crater

Forum Jump:

User Panel Messages

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