Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is good practice about python formatted string?

Tags:

python

file

Suppose I have a file on /home/ashraful/test.txt. Simply I 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')

The both way I can open file.

Thanks :)

like image 275
Mohammad Ashraful Islam Avatar asked Nov 29 '22 22:11

Mohammad Ashraful Islam


1 Answers

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

with open(os.path.join(os.path.expanduser('~'), 'test.txt')) as fp:
    # do your stuff with file
like image 182
armak Avatar answered Dec 02 '22 11:12

armak