Reputation: 11
I'm trying to modify specific words in a specific line so that the user can input which line they want to modify and which text they want to search and replace.
Here's my code:
def mod_apartment():
a = []
b = []
with open("Apartment_Details.txt", "r") as file:
for line in file:
a = line.split(",")
print(a)
with open("Apartment_Details.txt", "r") as file:
print("Enter line: ", end="")
lno = int(input())
lines = line[lno]
Output:
['0001', ' Trifolis', ' 900SQFT', ' A-A-A Impiana', ' Taman Garden', ' Kajang', ' Selangor', ' Furnished', ' Ready', ' Apartment', ' RM1700', ' Freehold', ' 7 August 2022', ' 6 August 2022', '\n']
['0002', ' Sky Suites ', ' 1000SQFT', ' Taman MingMing', ' Persinsin 2', ' Selangor', ' Kuala Lumpur ', ' Not Furnished ', ' Not Ready', ' Apartment', ' RM1000', ' Freehold ', ' 10 November 2022', ' 19 August 2022', '']
Enter line: 2
How do you append so that the user can modify line [0], and replace 0001 to 0003 for example.
Upvotes: 0
Views: 86
Reputation: 1361
You can use the following code to implement the desired functionality:
# read all lines
with open("Apartment_Details.txt", "r") as file:
lines = file.readlines()
line_i = int(input("Enter line: "))
# only splitting the line here, because we don't need to split the others
words = lines[line_i].split(",")
print(words)
word_i = int(input("Enter word position: "))
new_word = input("Enter replacement: "))
# replace the entry in words => that does not reflect to lines
words[word_i] = new_word
# therefore, also update lines (recombining the splitted words)
lines[line_i] = ",".join(words)
# write back to the file
with open("Apartment_Details.txt", "w") as file:
file.writelines(lines)
a = []
when overwriting it directly afterwards.for
blockwith
, you're not using the file. You need it of course when writing back to the fileline
variable in the second with
block is the last line in the file. It's "left over" from the for loop.Upvotes: 0
Reputation: 178
Is this ok for you?
def mod_apartment():
a = []
with open("Apartment_Details.txt", "r") as file:
for line in file:
b = line.split(",")
print(b)
a.append(b)
lno = int(input("\nEnter line index: "))
wdo = int(input("Enter word index: "))
word = input("Replace with: ")
a[lno][wdo] = word
print("\nNew lines:")
with open("Apartment_Details.txt", "w") as file:
for line in a:
print(line)
file.write(','.join(line))
Here the user has to write the row and word indices, but if you want to change it to the numbers of these objects, just replace this line:
a[lno - 1][wdo - 1] = word
Upvotes: 1