0

This is the data my file:

  • John Smith, 5
  • Luke Smith, 7
  • Mary Smith, 8
  • Boby Smith, 2

I want to be able to add another number onto a specific user in the file. See below (Mary).

  • John Smith, 5
  • Luke Smith, 7
  • Mary Smith, 8, 6
  • Boby Smith, 2

My code:

with open('filename.txt','a') as file:
    file.write("\n{}, {}".format(name,number))

This code will append/write to the file just fine, but it writes in new users each time, which I do not want it to do. I want it to check to see if a user is already in the file, and append that line with the new number. If user does not already exist, add them to the file.

Potter
  • 15
  • 6
  • You can't just insert stuff into a file. The safest way to do what you want is to read the whole file into memory, make your modifications, then write the modified version back to disk. If the file is *huge*, you can avoid re-writing the whole thing and just write from the point where your changes begin, but that's a little more complicated. – PM 2Ring Feb 20 '16 at 11:21
  • Hey, thanks for your advice on this. Could you point me in the right place/show me an example of this so I can try again please? Thank you. – Potter Feb 20 '16 at 11:28
  • PS, it's a small file – Potter Feb 20 '16 at 11:30
  • @Potter You would probably be better off using a .csv file rather than a .txt. – Rob Murray Feb 20 '16 at 11:31
  • @ R. Murray, thank you. I did try looking at doing it using .csv but there wasn't much on the web. I did manage to write into the csv, but came up against the same block - couldn't append the existing line, could only get it to insert new lines. – Potter Feb 20 '16 at 11:33
  • You will have to read the CSV, compare and rewrite it. There is no other way. The idea of inserting and modifying in place is what databases are for. – jsfan Feb 20 '16 at 11:41
  • You may find the answers here helpful: [Insert text in between file lines in python](http://stackoverflow.com/q/31261123/4014959). There _are_ actually a couple of ways to modify files using standard module functions. Check out the `fileinput` and `mmap` modules. However, be aware that if this is homework your teacher may not approve of such "advanced" techniques. – PM 2Ring Feb 20 '16 at 11:47

2 Answers2

1

Try this

value = 5
user = input('Please enter a username: ')

with open('myfile.txt', 'r+') as f:
    var = f.readlines()
    if user in ''.join(var):
        for count, line in enumerate(var):
            if user in line:
                found = line.strip() + ', ' + str(value) + '\n'
                var[count] = found
    else:
        '{} not in the file but has been added'
        var.append(user + ' ' + str(value) + '\n')

with open('myfile.txt', 'w') as f:
        f.writelines(var)

There should be a better way than opening the file twice, but it works

danidee
  • 9,298
  • 2
  • 35
  • 55
  • thanks - this is what I was looking for. The only question i have is how to I adjust the else to include a new name? The first part works as intended, but I would like to modify please so that it can handle a new name. Thanks! – Potter Feb 20 '16 at 13:36
  • So I have tried this: thelist = str([name, number]) .... else: var.append(thelist) but it overwrites everything in the file, instead of inserting a new line at the bottom.... Thanks – Potter Feb 20 '16 at 13:38
  • i've updated my answer, this time i used `readlines()` to read the whole file into memory. this is not very efficient if the file size is very huge but it should suffice for a case like yours – danidee Feb 20 '16 at 15:25
  • Hi danidee, just wanted to say thanks for all your help today. I've learned a lot and you've helped me out a lot - thanks! – Potter Feb 20 '16 at 16:25
1

This will work:

file = open('filename.txt','r')
file.read()
data = file.replace('Mary Smith, 8', 'Mary Smith, 8, 6')
file.close()
file = open('filename.txt', 'w')
file.write(data)
file.close()
Mark Skelton
  • 3,663
  • 4
  • 27
  • 47