Python Forum
Avoid hard-coded folderPath in the code (let users provide it)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Avoid hard-coded folderPath in the code (let users provide it)
#6
I do agree with @Gribouillis
Can show both way,as you should have used os.path.join() in your first code.
from os import path

file_path = 'C:\\foo'  #input("Enter the file path: ")
file_name = 'test.txt'  #input("Enter the file name with extension (.txt): ")
full_path =  path.join(file_path, file_name)

print(f"Full file address is: {full_path}")

#---------------------------------------------

from pathlib import Path

file_path = Path('C:\\foo') #Path(input("Enter the file path: ").strip())
file_name =  'test.txt' #input('Enter the file name with extension (.txt): ').strip()
file_full_path = file_path / file_name
print("Full file address is", file_full_path)
Output:
Full file address is: C:\foo\test.txt Full file address is C:\foo\test.txt
So the output is the "same" almost.
If look closer at it,so is the first one a string,
and second on a Path object that show it'a a Windows Path.
>>> full_path
'C:\\foo\\test.txt'

>>> file_full_path
WindowsPath('C:/foo/test.txt')
What if need that Path object should be a string?
The right way is to use os.fspath(path) and not str.
>>>import os

>>> os.fspath(file_full_path)
'C:\\foo\\test.txt'

>>> # Can also to it without import 
>>> file_full_path.__fspath__()
'C:\\foo\\test.txt'
Reply


Messages In This Thread
RE: Avoid hard-coded folderPath in the code (let users provide it) - by snippsat - Sep-06-2018, 09:02 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  output provide the filename along with the input file processed. arjunaram 1 938 Apr-13-2023, 08:15 PM
Last Post: menator01
  Avoid third party functions to wrote my python code into system debug-log? mark 9 2,213 Apr-09-2022, 08:41 PM
Last Post: mark
  Randomizer script to provide options based on user and priority cubangt 10 2,458 Mar-11-2022, 07:22 PM
Last Post: cubangt
  The count variable is giving me a hard time in this code D4isyy 2 1,975 Aug-09-2020, 10:32 PM
Last Post: bowlofred
  Having a hard time combining two parts of code. Coozeki 6 3,091 May-10-2020, 06:50 AM
Last Post: Coozeki
  How to avoid open and save a url every time I run code davidm 4 2,652 Mar-03-2020, 10:37 PM
Last Post: snippsat
  ARCPY enter excel table into coded domain Just_another_lost_man 6 3,755 Feb-23-2019, 09:23 PM
Last Post: buran
  How hard is this? Phillips45 0 2,110 Jun-11-2018, 05:49 PM
Last Post: Phillips45
  Is This Code Ok? How Can I Avoid Using Global Variables? digitalmatic7 9 5,821 Feb-15-2018, 09:32 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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