~1 min read • Updated Oct 1, 2025
Program Overview
This Python program reads multiple files and replaces their content directly.
It avoids using helper functions, external modules, or temporary buffers.
The replacement is done inline, using basic file I/O operations.
Python Code:
import os
# Read directory path and replacement text from user
directory = input("Enter directory path: ")
new_content = input("Enter new content to replace all files with: ")
# Replace content in all .txt files
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath) and filename.endswith(".txt"):
with open(filepath, "w") as file:
file.write(new_content)
print("\n--- All .txt files updated successfully ---")
Sample Output:
Enter directory path: ./data
Enter new content to replace all files with: Hello, Shahin
--- All .txt files updated successfully ---
Step-by-Step Explanation:
- The user provides a folder path and the replacement text
- The program loops through all files in the folder
- If a file ends with .txt, it opens the file in write mode and replaces its content
- No helper functions or external libraries are used
Written & researched by Dr. Shahin Siami