Let's say I have a text file containing:
Dan
Warrior
500
1
0
Is there a way I can edit a specific line in that text file? Right now I have this:
#!/usr/bin/env python
import io
myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('\n')[0]
try:
myfile = open('stats.txt', 'a')
myfile.writelines('Mage')[1]
except IOError:
myfile.close()
finally:
myfile.close()
Yes, I know that myfile.writelines('Mage')[1]
is incorrect. But you get my point, right? I'm trying to edit line 2 by replacing Warrior with Mage. But can I even do that?
If your text contains only one individual:
If your text contains several individuals:
import re
If the “job“ of an individual was of a constant length in the texte, you could change only the portion of texte corresponding to the “job“ the desired individual: that’s the same idea as senderle’s one.
But according to me, better would be to put the characteristics of individuals in a dictionnary recorded in file with cPickle:
You want to do something like this:
The reason for this is that you can't do something like "change line 2" directly in a file. You can only overwrite (not delete) parts of a file - that means that the new content just covers the old content. So, if you wrote 'Mage' over line 2, the resulting line would be 'Mageior'.
And then:
You can do it in two ways, choose what suits your requirement:
Method I.) Replacing using line number. You can use built-in function
enumerate()
in this case:First, in read mode get all data in a variable
Second, write to the file (where enumerate comes to action)
Method II.) Using the keyword you want to replace:
Open file in read mode and copy the contents to a list
"Warrior" has been replaced by "Mage", so write the updated data to the file:
This is what the output will be in both cases:
you can use fileinput to do in place editing
I have been practising working on files this evening and realised that I can build on Jochen's answer to provide greater functionality for repeated/multiple use. Unfortunately my answer does not address issue of dealing with large files but does make life easier in smaller files.