Created
May 13, 2020 15:56
-
-
Save phanthaihuan/13c76cd5cef3275207b838e7a21a7b55 to your computer and use it in GitHub Desktop.
How to replace text in file with Python
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
#!/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