Advertisement
Guest User

Replace string within file contents

a guest
Feb 22nd, 2012
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  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)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement