如果文件已经存在于输出目录(outputfile)中,则跳过代码

在运行代码之前检查输出目录(outputfile),以检查其中已经存在的文件!

import os
texttofind ='abcd'
texttoreplace ='wxyz'
sourcepath = os.listdir('inputfiles/')
for file in sourcepath:
    inputfile = 'inputfiles/'+ file
    print('conversion is ongoing for:' +inputfile)
    with open(inputfile,'r') as inputfile:
        filedata = inputfile.read()
        freq = 0
        freq = filedata.count(texttofind)
    destinationpath = 'outputfile/' + file
    filedata = filedata.replace(texttofind,texttoreplace)
    with open(destinationpath,'w') as file:
        file.write(filedata)
    print ('total %d Record replaced %freq')
iCMS 回答:如果文件已经存在于输出目录(outputfile)中,则跳过代码

像这样吗?

import os
texttofind ='abcd'
texttoreplace ='wxyz'
sourcepath = os.listdir('inputfiles/')
for file in sourcepath:
    destinationpath = 'outputfile/' + file
    if not os.path.isfile(destinationpath):
        inputfile = 'inputfiles/'+ file
        print('conversion is ongoing for:' +inputfile)
        with open(inputfile,'r') as inputfile:
            filedata = inputfile.read()
            freq = 0
            freq = filedata.count(texttofind)
    
        filedata = filedata.replace(texttofind,texttoreplace)
        with open(destinationpath,'w') as file:
            file.write(filedata)
        print ('total %d Record replaced %freq')
本文链接:https://www.f2er.com/1989528.html

大家都在问