![](/img/trans.png)
[英]Python: Is there a way to find and remove the first and last occurrence of a character in a string?
[英]Python3 find last occurrence string then write
我正在嘗試創建一個腳本,如果域不存在(最后出現###標記並寫入下一行),該腳本會將一個區域添加到named.conf的末尾。 我似乎陷入了列表與文件對象的悖論。 如果我以列表形式打開,則可以找到我的字符串,但是如果不先關閉列表對象就無法寫入文件,這不是一個好的解決方案。 如果我將文件作為文件對象打開,則在嘗試使用find時出現對象錯誤
Traceback (most recent call last):
File "named.py", line 10, in <module>
answer = mylist.find('#--#')
AttributeError: 'list' object has no attribute 'find'
要么
File "named.py", line 12, in <module>
f.write(" zone \""+name+"\" {\n")
io.UnsupportedOperation: not writable
在Python3中打開文件進行搜索和編輯的正確方法是什么?
import sys
import string
import os.path
name = input("Enter the domain to configure zone for? ")
#fd = open( "named.conf", 'w')
if os.path.lexists("named.conf"):
with open('named.conf') as f:
mylist = list(f)
print(mylist)
f.write(" zone \""+name+"\" {\n")
該文件僅開放供讀取,因此這就是您收到錯誤的原因,無論您使用in
還是==
取決於該行可以包含域名還是該行必須等於域名。
if os.path.lexists("named.conf"):
with open('named.conf') as f:
found = False
for line in f:
# if domain is in the line break and end
if name in line.rstrip():
found = True
break
# if found is still False we did not find the domain
# so open the file and append the domain name
if not found:
with open('named.conf', "a") as f:
f.write(" zone \{}\ {\n".format(name))
要查找最后出現的一行並在以下位置寫一行:
if os.path.lexists("named.conf"):
with open('named.conf') as f:
position = -1
for ind, line in enumerate(f):
# if line is #--#
if "#--#" == line.rstrip():
# keep updating index so will point to last occurrence at the end
position = ind
if position != -1: # if we found at least one match
with open('named.conf', "r+") as f:
for ind, line in enumerate(f):
if ind == position: # find same line again
# write line and new line
f.write("{}{}\n".format(line,your_new_line))
else:
f.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.