Replace string within file contents

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

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

相关标签:
8条回答
  • 2020-12-01 00:55

    Something like

    file = open('Stud.txt')
    contents = file.read()
    replaced_contents = contents.replace('A', 'Orange')
    
    <do stuff with the result>
    
    0 讨论(0)
  • 2020-12-01 01:02

    If you'd like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:

    I am using the with statement in this example, which closes the file after the with block is terminated - either normally when the last command finishes executing, or by an exception.

    def inplace_change(filename, old_string, new_string):
        # Safely read the input filename using 'with'
        with open(filename) as f:
            s = f.read()
            if old_string not in s:
                print('"{old_string}" not found in {filename}.'.format(**locals()))
                return
    
        # Safely write the changed content, if found in the file
        with open(filename, 'w') as f:
            print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
            s = s.replace(old_string, new_string)
            f.write(s)
    

    It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with statement.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-01 01:04
    with open("Stud.txt", "rt") as fin:
        with open("out.txt", "wt") as fout:
            for line in fin:
                fout.write(line.replace('A', 'Orange'))
    
    0 讨论(0)
  • 2020-12-01 01:07
    with open('Stud.txt','r') as f:
        newlines = []
        for line in f.readlines():
            newlines.append(line.replace('A', 'Orange'))
    with open('Stud.txt', 'w') as f:
        for line in newlines:
            f.write(line)
    
    0 讨论(0)
  • 2020-12-01 01:10
    #!/usr/bin/python
    
    with open(FileName) as f:
        newText=f.read().replace('A', 'Orange')
    
    with open(FileName, "w") as f:
        f.write(newText)
    
    0 讨论(0)
提交回复
热议问题