0

So, I am using this to replace a text odirx in a file and then writing it out to another file. But I would like the output file name to be sm_0120.txt instead of sm_template2.txt as well.

replacements = {'odirx':'0120'}

with open('/dir/sm_template.txt') as infile, open('/dir/sm_template2.txt', 'w') as outfile:
    for line in infile:
        for src, target in replacements.items():
            line = line.replace(src, target)
        outfile.write(line)

How can I do this?

It could write out the entire file after reading in, but I wanted to do this without reading in the whole file

Related: replacing text in a file with Python

TRIAL

I AM OKAY WITH READING IT IN IF THAT IS MY ONLY CHOICE

replacements = {'odirx':'0120'}

with open('/dir/sm_template.txt') as infile, open('/dir/sm_template2.txt', 'w') as outfile:
        for line in infile:
            for src, target in replacements.items():
                line = line.replace(src, target)
            lines.append(line)
            outfile = os.path.join(os.path.normpath(os.getcwd()+os.sep+"sm_"+os.sep+target+os.extsep+"txt"))

How can I write it out?

maximusdooku
  • 5,242
  • 10
  • 54
  • 94

2 Answers2

0

Unfortunately you'll have to write a new file since you are modifying it as part of a stream, there is no way around that

to clarify though, there do exist functions for copying files https://stackoverflow.com/a/123212/1699398

jmercouris
  • 348
  • 5
  • 17
0

Use os.rename:

os.rename('/dir/sm_template2.txt', '/dir/sm_0120.txt')
Hariom Singh
  • 3,512
  • 6
  • 28
  • 52