简体   繁体   中英

Replace a string with another string within a file in Python

You will be provided a file path for input I, a file path for output O, a string S, and a string T.

Read the contents of I, replacing each occurrence of S with T and write the resulting information to file O.

You should replace O if it already exists.

# Get the filepath from the command line
import sys
I= sys.argv[1] 
O= sys.argv[2] 
S= sys.argv[3]
T= sys.argv[4]

# Your code goes here

# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')

file2.replace(S, T)

file1.close()
file2.close()

file2= open('O', 'r')

print(file2)

Here's the error I keep getting:

Traceback (most recent call last): File "write-text-file.py", line 15, in file2.replace(S, T) AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'

Here is the code (Modified)

# Get the filepath from the command line
import sys
import re
I= sys.argv[1] 
O= sys.argv[2] 
S= sys.argv[3]
T= sys.argv[4]

# Your code goes here

# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')
data = file1.read()
data = data.replace(S, T)
file2.write(data)

file1.close()
file2.close()

file2= open(O, 'r')
data = file2.read()
print(data)

file2 is a file object not a string, file object's do not have replace method

try

with open(I, 'r') as file1, open(O, 'w') as file2:
    for line in file1.readlines():
        line=line.replace(S,T)
        file2.write(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM