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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With