蟒蛇;如何替换字符串模式并保存到文件,通过字符串变量从文件夹名称重命名文件到文件名?

时间:2014-08-03 09:05:17

标签: python string filenames

我在文件系统中为每个产品都有自己的文件夹;

/PRODUCTS/PRODUCT_XXX

/PRODUCT_001
/PRODUCT_002
/PRODUCT_003
/PRODUCT_004
/PRODUCT_005
...
/PRODUCT_999

每个文件夹都有PRODUCT_XXX.html文件以及产品的图片和数据......

我不想重拍所有的PRODUCT_XXX.html文件,

如果我想改变html的布局......

我想在根文件夹中有一个PRODUCT_XXX.html文件,

/PRODUCTS/PRODUCT_XXX.html

然后将其复制到所有产品编号文件夹, 仅替换模式XXX - >来自FOLDER NAME的产品编号

prodnum = "555"    #  Actually,  would need to read the Product Number from the OS
                   folder name..
               #  But will do that later,  after I get this on the below working...

f1 = open('PRODUCT_XXX.html', 'r')
f2 = open('/PRODUCT_%D/PRODUCT_%D.html', prodnum, 'w'  )
for line in f1:
    f2.write(line.replace('PRODUCT_XXX', 'PRODUCT_%D', prodnum))
                # (then later could do also other things here..)
f1.close()
f2.close()

我正在尝试%D,%s ...但无法保存PRODUCT_555.html文件 如何通过字符串变量名保存文件?试图谷歌一些例子,但那些似乎很难找到..

3 个答案:

答案 0 :(得分:2)

您错过%,例如

f2.write(line.replace('PRODUCT_XXX', 'PRODUCT_%d' % prodnum)) # note lowercase d

但使用str.format

会更清晰,更不容易出错
f2.write(line.replace('PRODUCT_XXX', 'PRODUCT_{0}'.format(prodnum)))

答案 1 :(得分:0)

你想要这个:

f2 = open('/PRODUCT_{0}/PRODUCT_{0}.html'.format(prodnum), 'w')

答案 2 :(得分:0)

如果我有一个index_numbers.txt,数字1,2,3,4,5,6,... 1000一行一个数字;

  import shutil
  file_read = open("index_numbers.txt", 'r')


  def do_the_thing(indexnum):
     print(indexnum)
     file1 = open("fileXXX.html", 'r')
     file2 = open("file{0}.html".format(indexnum), 'wb')

     for line in file1:
        file2.write(line.replace('XXX', '%s' % indexnum))   

     file1.close()
     file2.close()


  line_from_file = file_read.readline()

     for line_from_file in file_read:
       print(line_from_file) 
       line_from_file = line_from_file[0:-1]
       indexnum = line_from_file

       shutil.copy2('fileXXX.html', 'file{0}.html'.format(indexnum))

       do_the_thing(indexnum)

   file_read.close() 

这样的东西会做什么?
但是,如果想要替换文件中的更多文本字段,如何修改此脚本;

   -  replace the XXX with the index number
   -  replace the YYY with Product short name
   -  replace the ZZZ with Product long name
   -  ...