Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

Replace string within file contents

By: a guest on Feb 22nd, 2012  |  syntax: None  |  size: 1.25 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. with open("out.txt", "wt") as out:
  2.     for line in open("Stud.txt"):
  3.         out.write(line.replace('A', 'Orange'))
  4.        
  5. with open('Stud.txt','r') as f:
  6.     newlines = []
  7.     for line in f.readlines():
  8.         newlines.append(line.replace('A', 'Orange'))
  9. with open('Stud.txt', 'w') as f:
  10.     for line in newlines:
  11.         f.write(line)
  12.        
  13. text_file = open("file.txt", "rw")
  14. whole_thing = text_file.read()
  15. whole_thing = whole_thing.replace("A", "Orange");
  16. text_file.write(whole_thing);
  17. text_file.close();
  18.        
  19. file = open('Stud.txt')
  20. contents = file.read()
  21. replaced_contents = contents.replace('A', 'Orange')
  22.  
  23. <do stuff with the result>
  24.        
  25. import re
  26.  
  27. input = file('C:full_pathStud.txt), 'r')
  28. #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.
  29.  
  30. saved_input
  31. for eachLine in input:
  32.     saved_input.append(eachLine)
  33.  
  34. #now we change entries with 'A' to 'Orange'
  35. for i in range(0, len(old):
  36.     search = re.sub('A', 'Orange', saved_input[i])
  37.     if search is not None:
  38.         saved_input[i] = search
  39. #now we open the file in write mode (clearing it) and writing saved_input back to it
  40. input = file('C:full_pathStud.txt), 'w')
  41. for each in saved_input:
  42.     input.write(each)