Which one is good practice about python formatted string?

Suppose I have a file on /home/ashraful/test.txt. I just just want to open the file. Now my question is:

which one is good practice?

Solution 1:

dir = "/home/ashraful/"
fp = open("{0}{1}".format(dir, 'test.txt'), 'r')

Solution 2:

dir = "/home/ashraful/"
fp = open(dir + 'test.txt', 'r')

In both cases, I can open the file.

Thank:)

+4
source share
3 answers

instead of concatenating the string, use os.path.join os.path.expanduserto generate the path and open the file. (assuming you are trying to open the file in your home directory)

with open(os.path.join(os.path.expanduser('~'), 'test.txt')) as fp:
    # do your stuff with file
+14
source

, /, , os.path.join(). , Python - , . PEP 310:

PEP     , %     .

+4

I think the best way would be for us os.path.join () here

import os.path

#…
dir = '/home/ashraful/'
fp = open(os.path.join(dir, 'test.txt'), 'r')
+2
source

Source: https://habr.com/ru/post/1655800/


All Articles