简体   繁体   中英

Python; how to replace string pattern and save to a file, rename the file by string variable from folder name to the filename?

I have own folder for each product in the filesystem;

/PRODUCTS/PRODUCT_XXX

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

Each folder have PRODUCT_XXX.html file and picture and data of the product...

I would not wan't to remake all the PRODUCT_XXX.html files,

if I would like to change the layout of the html...

I would like to have one PRODUCT_XXX.html file at the root folder,

/PRODUCTS/PRODUCT_XXX.html

then copy it to all of the product number folders, replacing just the pattern XXX --> the product number from the 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()

I was trying %D, %s ... but was not able to get save the PRODUCT_555.html file How to save file by string variable name? Tried to google some example, but those seems hard to find..

You're missing % , eg

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

But this would be clearer and less error-prone using str.format :

f2.write(line.replace('PRODUCT_XXX', 'PRODUCT_{0}'.format(prodnum)))

你要这个:

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

If I have a index_numbers.txt, with numbers 1, 2, 3, 4, 5, 6, ... 1000 one number at one line;

  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() 

Something like that would do the thing?
But how to modify this script, if one would like to replace more text fields in file;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM