Skip to content

Instantly share code, notes, and snippets.

@itkr
Created August 3, 2015 10:43
Show Gist options
  • Save itkr/81ac4f315c888ac4b668 to your computer and use it in GitHub Desktop.
Save itkr/81ac4f315c888ac4b668 to your computer and use it in GitHub Desktop.
replace file
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)
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)
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