Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filename by join string in Python

Tags:

python

php

I have a simple code line in Python, use too many + is not nice

filename = path + '/static/' + folder + '/' + name + 'html'

Can be like that in php

$filename = "$path/static/$folder/{$name}html"

So how we write shorten in Python?


2 Answers

What you want is join the path components. To do this you can use the os.path.join() function which uses os.sep as separator.

>>> import os
>>> path = 'workspace'
>>> folder = 'stackoverflow'
>>> name = 'layout'
>>> os.path.join(path, 'static', folder, name, 'html')
'workspace/static/stackoverflow/layout/html'

You can also use PurePath if you are using Python 3.4 or newer.

from pathlib import PurePath

p = PurePath(path)
filename = str(p / static / folder / name / 'html')

Demo:

>>> from pathlib import PurePath
>>> p = PurePath(path)
>>> filename = str(p / 'static' / folder / name / 'html')
>>> filename
'workspace/static/stackoverflow/layout/html'
like image 140
styvane Avatar answered Dec 05 '25 02:12

styvane


You can do this in python which would be much more readable,

filename = "{}/static/{}/{}html".format(path, folder, name)
like image 23
Vishnu Nair Avatar answered Dec 05 '25 03:12

Vishnu Nair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!