O
O
OliviaDunham112020-03-12 12:32:20
JavaScript
OliviaDunham11, 2020-03-12 12:32:20

How to do a replace on a file?

Task: there is a file. It needs to replace all the words CHLB with EKAT. And then save this content to a new file with a new name.

-проверить файл с нужным расширением и форматом

    -создать новое назв файла заменой подстроки

    -открывает, читаем в текст, заменяем текст

    -сохранить текст в файл с новым назв

    """

 

import os

import shutil

from os import path

 

texttofind='CHLB'

 

texttoreplace='EKAT'

 

sourcepath = os.listdir('C:\\GIT\\sandbox\\airflow\\dags\\tst\\Queries\\')

 

for file in sourcepath:

 

    if m.endswith('.sql'):

        inputfile='C:\\GIT\\sandbox\\airflow\\dags\\tst\\Queries\\'+file

        print('Conversion in ongoing for: ' + inputfile)

       

        count = 0

        for line in fileinput.input(["a.txt"], inplace=True, backup='.bak'):

            if 'red' in line:

                no_of_red=line.count('red')

                sys.stdout.write(line.replace('red','RED'))

                count += no_of_red

    else:

        sys.stdout.write(line)

 

        with open ('Ctl_Chlb_RV_Hub_JobLedgerEntry.txt', 'w') as f:

        f.write(new_data)

   

    with open(inputfile,'r') as inputfile:

        filedata=inputfile.read()

        freq=0

        fred=filedata.count(texttofind)

       

    destinationpath='C:\\GIT\\sandbox\\airflow\\dags\\tst\\Queries\\' + file

    filedata=filedata.replace(texttofind,texttoreplace)

   

    with open(destinationpath, 'w') as file:

        file.write()

       

  file.close()

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Derepko, 2019-08-04
@teertsneerg

if(member(message.author)) {
     console.log(message);  //Первый вызов
     request.post({url:'http://url.ru/', form: {new:'1', id:id, link:link}}, (err,httpResponse,body) => { 
    console.log(message);  //Второй вызов
    })
}

S
Sergey Pankov, 2020-03-12
@OliviaDunham11

Yes, you can do it with python from the command line:

py -x "x.replace('WHAT', 'TOWHAT')" < inputfile.txt > outputfile.txt

This is if the file is text. If binary, then a little differently, but in binary you need to carefully change this, the format may float.
If you need to exclude the replacement of the same characters as part of other words, then like this:
py -x "re.sub('(\W)What(\W)', '\\\1ToWhat\\\2', x)"" < inputfile.txt > outputfile.txt

A
alternativshik, 2020-03-12
@alternativshik

Or you can not invent bicycles, but do it via sed from the command line

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question