Created
August 3, 2015 10:43
-
-
Save itkr/81ac4f315c888ac4b668 to your computer and use it in GitHub Desktop.
replace file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import os | |
def replace_csv_file(file_path, old_str, new_str): | |
count = 0 | |
temp_path = '_' + file_path | |
with open(file_path, 'r') as read_file: | |
with open(temp_path, 'w') as write_file: | |
reader = csv.reader(read_file) | |
writer = csv.writer(write_file, lineterminator='\n') | |
for row in reader: | |
count += 1 | |
try: | |
writer.writerow( | |
[col.replace(old_str, new_str) for col in row]) | |
except: | |
print 'Error Line: {}'.format(count) | |
raise | |
os.remove(file_path) | |
os.rename(temp_path, file_path) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def replace_file(file_path, old_str, new_str): | |
with open(file_path) as io: | |
io.seek(0) | |
rep = io.getvalue().replace(old_str, new_str) | |
io.truncate() | |
io.write(rep) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
def replace_text_file(file_path, old_str, new_str): | |
count = 0 | |
temp_path = '_' + file_path | |
with open(file_path, 'r') as read_file: | |
with open(temp_path, 'w') as write_file: | |
for read_line in read_file: | |
count += 1 | |
try: | |
write_file.write(read_line.replace(old_str, new_str)) | |
except: | |
print 'Error Line: {}'.format(count) | |
raise | |
os.remove(file_path) | |
os.rename(temp_path, file_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment