faqts : Computers : Programming : Languages : Python : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

18 of 24 people (75%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

how to copy a file and at the same time i want to change some text to the newfile

Jul 8th, 2003 04:35
Michael Chermside, chempaka biru,


If you simply wanted to copy the file from one place to another, then 
it's probably simplest and fastest if you use some of the file handling 
tools that come with Python, such as the copy() function from the 
shutil module.
But if you want to modify the contents as you go, then what you want is 
a basic read-modify-write loop. The most common version of this is when 
you can perform your modifications line-by-line. Then it looks 
something like this:
    # Syntax for Python 2.2 or better
    def copyAndModify(inFileName, outFileName):
        inFile = open(inFileName, 'r')
        outFile = open(outFileName, 'w')
        for inLine in inFile:
            outLine = modifyLine( inLine )
            outFile.write( outLine )
        inFile.close()
        outFile.close()
If you can't do your changes line-by-line, then you will probably use 
some modification of this. For instance, if your modification needed to 
operate on the entire file at once (and you only needed to handle files 
small emough to fit in memory), then you could use this version:
    def copyAndModify(inFileName, outFileName):
        inFile = open(inFileName, 'r')
        inText = inFile.read()
        inFile.close()
        outText = modifyFile( inText )
        outFile = open(outFileName, 'w')
        outFile.write()
        outFile.close()
You can build your own solution on top of these examples.