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
Question [SOLVED] Open file, and insert space in string? Winfried 7 2,466 May-28-2025, 07:56 AM
Last Post: Winfried
  Trying to open depracated joblib file mckennamason 0 2,010 Sep-19-2024, 03:30 PM
Last Post: mckennamason
  Open/save file on Android frohr 0 2,082 Jan-24-2024, 06:28 PM
Last Post: frohr
  file open "file not found error" shanoger 8 16,024 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 2,635 Aug-14-2023, 05:04 PM
Last Post: snippsat
  I cannot able open a file in python ? ted 5 15,033 Feb-11-2023, 02:38 AM
Last Post: ted
  testing an open file Skaperen 7 3,568 Dec-20-2022, 02:19 AM
Last Post: Skaperen
  Code Assistance needed in saving the file MithunT 0 1,726 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 2,621 May-06-2022, 01:44 PM
Last Post: Larz60+
  Dynamic File Name to a shared folder with open command in python sjcsvatt 9 12,479 Jan-07-2022, 04:55 PM
Last Post: bowlofred

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.