[英]How to modify specific text in a specific line in a text file
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: 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.您如何 append 以便用户可以修改行 [0],例如将 0001 替换为 0003。
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
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.之后直接覆盖时无需设置a = []
。for
block只有您存储在 a 上的最后一个值(最后一行)在for
块之后可用with
, you're not using the file.你不需要第二with
,你没有使用该文件。 You need it of course when writing back to the file写回文件时当然需要它line
variable in the second with
block is the last line in the file.第二个with
块中的line
变量是文件中的最后一行。 It's "left over" from the for loop.它是 for 循环的“剩余”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.