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

时间:2013-03-31 19:08:29

标签: python file-io text-files

我希望我不会转发(我事先做过研究),但我需要一些帮助。

所以我会尽可能地解释这个问题。

我有一个文本文件,在其中我有这种格式的信息:

a 10
b 11
c 12

我读取此文件并将其转换为字典,第一列为键,第二列为值。

现在我正在尝试相反的做法,我需要能够以相同的格式用修改后的值写回文件,用空格分隔键,然后是相应的值。

为什么我要这样做?

嗯,用户使用该程序可以更改所有值。因此,当决定更改值时,我需要将它们写回文本文件。

这就是问题所在,我只是不知道该怎么做。

我该怎么做呢?

我现在有了读取值的当前代码:

T_Dictionary = {}
    with open(r"C:\NetSendClient\files\nsed.txt",newline = "") as f:
        reader = csv.reader(f, delimiter=" ")
        T_Dictionary = dict(reader)

2 个答案:

答案 0 :(得分:0)

这样的事情:

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()

你必须做出一些改变,但它与你想做的事情非常相似。中号

答案 1 :(得分:0)

好吧,假设字典名为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])

我希望它有所帮助

相关问题