[英]How to write to a specific line in a text file
我希望我不要轉發(我之前做了研究),但是我需要一點幫助。
因此,我將盡力解釋這個問題。
我有一個文本文件,並且在其中有以下格式的信息:
a 10
b 11
c 12
我閱讀了此文件,並將其轉換為字典,第一列為鍵,第二列為值。
現在,我試圖做相反的事情,我需要能夠將修改后的值以相同的格式寫回文件,鍵之間用空格分隔,然后是相應的值。
我為什么要這樣做?
好吧,所有值都應該由用戶使用該程序更改。 因此,當do決定更改值時,我需要將它們寫回到文本文件中。
這就是問題所在,我只是不知道該怎么做。
我該怎么做呢?
我有我的當前代碼可在此處讀取值:
T_Dictionary = {}
with open(r"C:\NetSendClient\files\nsed.txt",newline = "") as f:
reader = csv.reader(f, delimiter=" ")
T_Dictionary = dict(reader)
像這樣:
def txtf_exp2(xlist):
print("\n", xlist)
t = open("mytxt.txt", "w+")
# combines a list of lists into a list
ylist = []
for i in range(len(xlist)):
newstr = xlist[i][0] + "\n"
ylist.append(newstr)
newstr = str(xlist[i][1]) + "\n"
ylist.append(newstr)
t.writelines(ylist)
t.seek(0)
print(t.read())
t.close()
def txtf_exp3(xlist):
# does the same as the function above but is simpler
print("\n", xlist)
t = open("mytext.txt", "w+")
for i in range(len(xlist)):
t.write(xlist[i][0] + "\n" + str(xlist[i][1]) + "\n")
t.seek(0)
print(t.read())
t.close()
您必須進行一些更改,但這與您嘗試執行的操作非常相似。 中號
好吧,假設字典叫做A,文件是text.txt,我會這樣做:
W=""
for i in A: # for each key in the dictionary
W+="{0} {1}\n".format(i,A[i]) # Append to W a dictionary key , a space , the value corresponding to that key and start a new line
with open("text.txt","w") as O:
O.write(W)
如果我理解你在問什么。
但是,使用此方法會在文件末尾留空行,但是可以替換掉
O.write(W)
與
O.write(W[0:-1])
我希望它有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.