Replace string within file contents

后端 未结 8 1750
不知归路
不知归路 2020-12-01 00:28

How can I open a file, Stud.txt, and then replace any occurences of \"A\" with \"Orange\"?

8条回答
  •  萌比男神i
    2020-12-01 01:02

    easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...

    import re
    
    input = file('C:\full_path\Stud.txt), 'r')
    #when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file.  So we have to save the file first.
    
    saved_input
    for eachLine in input:
        saved_input.append(eachLine)
    
    #now we change entries with 'A' to 'Orange'
    for i in range(0, len(old):
        search = re.sub('A', 'Orange', saved_input[i])
        if search is not None:
            saved_input[i] = search
    #now we open the file in write mode (clearing it) and writing saved_input back to it
    input = file('C:\full_path\Stud.txt), 'w')
    for each in saved_input:
        input.write(each)
    

提交回复
热议问题