The user is writing a code that enters the content in a text file and modifies the content.
command = int(input("(1. input 2. edit) >> "))
if command == 1:
pattern_input = str(input("pattern >> ")).lower()
template_input = str(input("template >> ")).lower()
pattern = "<pattern>" + pattern_input + "</pattern>"
content = ""
if ";" in template_input:
template_list = template_input.split("; ")
for i in template_list:
content += "<li>" + i + "</li>" + "\n"
template = "<template>" + "<random>" + "\n" + content + "</random>" + "</template>"
else:
content = template_input
template = "<template>" + content + "</template>"
category = "<category>" + pattern + "\n" + template + "</category>"
with open('file.txt', 'a+t') as f:
f.write(category + "\n")
print(category)
I'm going to proceed like this, but when I read the file,
I'd appreciate your help.
python
: It is recommended to use read in the situation you asked.
Read is a function that brings up the entire text, and readlines is a function that divides the line by line.
The following is an example of a comparison between two functions.
with open('test.txt', 'r') as f:
print(f.read()) # King Sejong\nHunminjeongeum\nHangul
f.seek(0)
print(f.readlines()) # ["King Sejong\n", "Hunminjeongeum\n", "Hangul"]
It is efficient to load the entire text through the read function and use replace to change the sentence.
: It is possible with 'r+'.
However, it is a way to modify it by adding it to the back of existing text like 'a+'. Please refer to it.
with open('test.txt', 'r+') as f:
print(f.read()) # King Sejong
f.write('Hunminjeongeum') #Edited as 'King Sejong's Hunminjeongeum'
: Yes.
The use of the if
syntax is correct to 'check' for the existence of a particular sentence rather than 'find' a particular sentence.
: Yes.
It's the simplest and most reliable way.
© 2025 OneMinuteCode. All rights reserved.