Problem: You use Python in a terminal and you want to replace a string
'example' in a text file
xxxxx example xxxxx
Your goal is to accomplish the following text:
xxxxx replaced_example xxxxx
In particular, you want to open the file, replace the text, and rewrite the result into the file—all in a single line of Python code!
Can a Python one-liner accomplish this?
Let’s see how you can accomplish this task as a Python one-liner!
Method 1: Print to Standard Input
The first method is best if you want to replace all occurrences of
"replaced_example" and print the result to the standard input.
python -c "print(open('file.txt').read().replace('example','replaced_example'))"
The replace method replaces all occurrences of the first argument with the second argument. It returns the new string. You can now print the result to the stdin or write it back to a file.
Method 2: Print to File
The second method is best if you want to replace all occurrences of
"replaced_example" and write the result to a new file
python -c "print(open('file.txt').read().replace('example','replaced_example'), file=open('file2.txt', 'w'))"
The replace method replaces all occurrences of the first argument with the second argument. It returns the new string. You can now print the result to the file with means of the
file argument of the print function.
Method 3: exec()
You can always convert a multi-liner into a one-liner using the exec() function. Say, you have the following multiline script to replace all occurrences of a string in a file:
with open('file.txt', 'r') as f: s = f.read().replace('example', 'replaced_example') with open('file.txt', 'w') as f: f.write(s)
You first open the file in read mode reading all its contents and creating the new string with replaced occurrences of the string
'example'. After that, you open the file in writing mode to overwrite its contents.
You use the
exec() function to one-linerize this script:
exec("with open('file.txt', 'r') as f:\n s = f.read().replace('example', 'replaced_example')\nwith open('file.txt', 'w') as f:\n f.write(s)")
All you did is to replace the new lines with the new line character
\n. This resulting script is a not-so-concise one-liner to replace all contents of a given file!
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.