简体   繁体   中英

How to write to a specific line in a text file

I hope I'm not reposting (I did research before hand) but I need a little help.

So I'll explain the problem as best as I can.

I have is a text file, and inside it I have information in this format:

a 10
b 11
c 12

I read this file and convert it to a dictionary with the first column as the key, and the second as the value.

Now I'm trying to do the opposite, I need to be able to write the file back with modified values in the same format, the key separated by a space, then the corresponding value.

Why would I want to do this?

Well, all the values are supposed to be changeable by the user using the program. So when the do decide to change the values, I need them to be written back to the text file.

This is where the problem is, I just don't know how to do it.

How might I go about doing this?

I've got my current code for reading the values here:

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

Something like this:

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

You'll have to make some changes, but it's very similar to what you're trying to do. M

ok,supposing the dictionary is called A and the file is text.txt i would do that:

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)

if i understood what you were asking.
however using this method would leave an empty line at the end of the file ,but that can be removed replacing

O.write(W)

with

O.write(W[0:-1])

i hope it helped

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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