繁体   English   中英

如何写入文本文件中的特定行

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM