使用变量创建文件名

时间:2015-11-19 10:49:32

标签: python variables

我对Python很陌生,仍在努力解决问题。我需要连接大量的数据文件,但首先我需要将要合并的文件的名称写入文本文件,以便我可以在下一个代码中调用它们。这将是不同的年份,所以我能够将变量'years'设置为我想要的年份,因此它会更改我的代码中的所有文件。这就是我现在所拥有的:

year = '07'

filenames = ['gdas1.jan"year".w1', 'gdas1.jan"year".w2','gdas1.jan"year".w3', 'gdas1.jan"year".w4', 'gdas1.jan"year".w5']
with open('D:/hysplitmergeoutput/hysplitnames"year"', 'w') as outfile:
for fname in filenames:
    with open(fname) as infile:
        for line in infile:
            outfile.write(line)

print hysplitnames"year"

3 个答案:

答案 0 :(得分:0)

您应该查看字符串formatting functions

答案 1 :(得分:0)

您可以这样使用地图功能:

year = "07"
filenames = ['gdas1.janYEAR.w1', 'gdas1.janYEAR.w2','gdas1.janYEAR.w3']
filenames_yeared = map(lambda x: x.replace("YEAR", year), filenames)

你会得到这个:

['gdas1.jan07.w1', 'gdas1.jan07.w2','gdas1.jan07.w3']

这是你在找什么?

答案 2 :(得分:0)

您可以使用字符串格式。 例如,如果要替换整数,则必须使用标识符%i like:

a = 1
b = "newstring%i" % a # print b --> "newstring1"

对于你的情况:

for year in range(7,15,1):
   # year string
   if year<10: 
         year_str = "0%i" % year
   else: 
         year_str = "%i" % year


   # Build the array of filenames
   filenames = ["gdas1.jan%s.w" % year_str +  str(k) for k in range(1,6)]

   with open('D:/hysplitmergeoutput/hysplitnames%s' % year_str, 'w') as outfile:
        for fname in filenames:
            with open(fname) as infile:
                for line in infile:
                    outfile.write(line)

   print hysplitnames+"%s" % year_str

字符串的标识符为%s,浮点数为%.4f(包含4位数字)。