0

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)
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
Micrified
  • 3,338
  • 4
  • 33
  • 59
  • The best way is to create a new file, http://stackoverflow.com/questions/4719438/editing-specific-line-in-text-file-in-python – Ashwini Chaudhary Mar 31 '13 at 19:16
  • If you are doing these file/dictionary conversions for data persistence you may want to consider using JSON, pickle, or even a DB like sqlite3. – Jared Mar 31 '13 at 19:19

2 Answers2

0

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

mistermarko
  • 305
  • 1
  • 3
  • 20
  • Hey, could you perhaps explain to me how this works? I'm unfamiliar with 'xlist'. What does it do when it print's a new line, and then xlist? – Micrified Mar 31 '13 at 22:08
  • Xlist is just a list of lists where each sub-list is a string and a number. Each string and each number is written on a new line, which is what he would have to modify. I should have included an example list. – mistermarko Apr 03 '13 at 15:02
0

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

Alberto Perrella
  • 1,318
  • 5
  • 12
  • 19
  • 1. why `tuple(A.key())`, you can simply iterate over the dict: `for i in A` . 2. use string formatting instead of `str()` : `"{0} {1}\n".format(i,A[i])`. 3.Always use the `with` statement for opening files. – Ashwini Chaudhary Mar 31 '13 at 19:43
  • There's no need of `O.close()`, that's the whole point of using `with` statement. Plus you can also place that for loop inside the `with` statement and write the text to the file with every iteration(instead of concatenating to a string). And considering the fact that dictionaries don't maintain any order so this program may create a file with different order than the original file. – Ashwini Chaudhary Mar 31 '13 at 20:44
  • isn't concatenating a string faster than writing more times on a file? and i think that mantaining the order of the previous file isn't needed;however sorry,it's the first time i am using "with" ,how ignorant :\ – Alberto Perrella Mar 31 '13 at 21:11
  • @AlbertoPerrella Maintaing order is not needed, no. – Micrified Apr 01 '13 at 01:12