关于python格式化字符串,哪一个是好习惯?

时间:2016-09-26 07:16:31

标签: python file

假设我在/home/ashraful/test.txt上有一个文件。我只是想打开文件。 现在我的问题是:

哪一个是好习惯?

解决方案1:

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

解决方案2:

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

这两种方式我都可以打开文件。

谢谢:)

3 个答案:

答案 0 :(得分:14)

而不是连接字符串使用os.path.join os.path.expanduser来生成路径并打开文件。 (假设您尝试在主目录中打开文件)

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

答案 1 :(得分:4)

如果您的目标是打开文件/目录,正如其他人所提到的那样,您应该使用os.path.join()方法。但是,如果你想在Python中格式化字符串 - 正如你的问题标题所示 - 那么你应该首选你的第一种方法。引用PEP 310

  

本PEP提出了一种用于内置字符串格式化的新系统       用于替换现有'%'字符串的操作       格式化运算符。

答案 2 :(得分:2)

我认为最好的方法是在这里使用os.path.join()

import os.path

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