Python Program to Replace Characters in a File (a→b, z→a, A→B, Z→A)
This Python program accepts user input, stores it in a file, replaces alphabet characters (a→b, z→a, A→B, Z→A), prints each conversion, and updates the same file.
Python Program for Character Replacement in a File
In this tutorial, we will learn how to create a Python program that:
- Takes input from the user
- Writes the input into a file
- Replaces characters as follows:
- a → b, b → c, ..., z → a
- A → B, B → C, ..., Z → A
- Other characters remain unchanged
The program also prints each character conversion on the screen and updates the same file.
Python Program Code
text = input("Enter content for file: ")
# Write original content to file
with open("input.txt", "w") as file:
file.write(text)
print("\nCharacter Conversion:\n")
# Read, convert, print and overwrite the same file
with open("input.txt", "r+") as file:
data = file.read()
result = ""
for ch in data:
new_ch = ch
if 'a' <= ch <= 'y':
new_ch = chr(ord(ch) + 1)
elif ch == 'z':
new_ch = 'a'
elif 'A' <= ch <= 'Y':
new_ch = chr(ord(ch) + 1)
elif ch == 'Z':
new_ch = 'A'
if ch != new_ch:
print(f"{ch} -> {new_ch}")
result += new_ch
file.seek(0)
file.write(result)
file.truncate()
print("\nFile updated successfully.")
How the Program Works
- User enters text using input()
- The text is saved into a file
- The file is reopened in r+ mode
- Each character is checked and replaced if required
- Conversions are printed on the screen
- The same file is updated with modified content
Sample Output
Input: aZz Hello Output on Screen: a -> b Z -> A z -> a H -> I Final File Content: bAa Ifmmp
Conclusion
This program is very useful for understanding Python file handling, ASCII character manipulation, and real-time data conversion. It is especially important for O Level and Python practical examinations.