Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- input_data = open('input.txt','r') #this opens the file to read it.
- output_data = open('output.txt','w') #this opens a file to write to.
- userStr= (raw_input('Enter the word to be replaced:')) #this prompts the user for a word
- userReplace =(raw_input('What should I replace all occurences of ' + userStr + ' with?')) #this prompts the user for the replacement word
- for line in input_data:
- words = line.split()
- if userStr in words:
- output_data.write(line + userReplace)
- else:
- output_data.write(line)
- print 'All occurences of '+userStr+' in input.txt have been replaced by '+userReplace+' in output.txt' #this tells the user that we have replaced the words they gave us
- input_data.close() #this closes the documents we opened before
- output_data.close()
- if userStr in words:
- output_data.write(line + userReplace) # <-- Right here
- else:
- output_data.write(line)
- for line in input_data:
- while userStr in line:
- index = line.index(userStr) # The place where `userStr` occurs in `line`.
- # You need to cut `line` into two parts: the part before `index` and
- # the part after `index`. Remember to consider in the length of `userStr`.
- line = part_before_index + userReplace + part_after_index
- output_data.write(line + 'n') # You still need to add a newline
- output_data.write(userReplace.join(line.split(userStr)))
Add Comment
Please, Sign In to add comment