Skip to content

Instantly share code, notes, and snippets.

@phanthaihuan
Created May 13, 2020 15:56
Show Gist options
  • Save phanthaihuan/13c76cd5cef3275207b838e7a21a7b55 to your computer and use it in GitHub Desktop.
Save phanthaihuan/13c76cd5cef3275207b838e7a21a7b55 to your computer and use it in GitHub Desktop.
How to replace text in file with Python
#!/usr/bin/env python
import os
import subprocess
PWD = os.getcwd()
file_name = 'data.txt'
file_path = os.path.join(PWD, file_name)
def replaceTextInFile(file_path, oldText, newText):
# Read in the file
with open(file_path) as file:
file_data = file.read()
# Replace the target string
file_data = file_data.replace(oldText, newText)
# Write the file out again
with open(file_path, 'w') as file:
file.write(file_data)
replaceTextInFile(file_path, 'Khoai To', '')
os.system('cat data.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment