Python adding text at the line
Question: I have a file which contains following row:

    
    
    //hva_SaastonJakaumanMuutos/printData/reallocationAssignment/changeUser/firstName>
    

I want to add "John" at the end of line.

I have written following code but for some reason it is not working,

    
    
    def add_text_to_file(self, file, rowTitle, inputText):
        f = open("check_files/"+file+".txt", "r")
        fileList = list(f)
        f.close()
    
        j = 0
        for row in fileList :
            if fileList[j].find(rowTitle) > 0 :
                fileList[j]=fileList[j].replace("\n","")+inputText+"\n"
                break
            j = j+1
    
        f = open("check_files/"+file+".txt", "w")
        f.writelines(fileList)
        f.close()
    

Do you see where am I doing wrong?


Answer: `str.find` may return `0` if the text you are searching is found at the
beginning. After all, it returns the index the match begins.

So your condition should be:

    
    
    if fileList[j].find(rowTitle) >= 0 :
    

**Edit:**

The correction above would save the day but it's better if you things the
_right_ way, the pythonic way.

  * If you are looking for a substring in a text, you can use the `foo in bar` comparison. It will be `True` if `foo` can be found in `bar` and `False` otherwise.
  * You rarely need a counter in Python. `enumerate` built-in is your friend here.
  * You can combine the iteration and writing and eliminate an unnecessary step.
  * `strip` or [`rstrip`](http://docs.python.org/library/stdtypes.html#str.rstrip) is better than replace in your case. 
  * For Python 2.6+, it is better to use `with` statement when dealing with files. It will deal with the closing of the file right way. For Python 2.5, you need `from __future__ import with_statement`
  * Refer to [PEP8](http://www.python.org/dev/peps/pep-0008/) for commonly preferred naming conventions.

Here is a cleaned up version:

    
    
    def add_text_to_file(self, file, row_title, input_text):
        with open("check_files/" + file + ".txt", "r") as infile:
            file_list = infile.readlines()
    
        with open("check_files/" + file + ".txt", "w") as outfile:
            for row in file_list:
                if row_title in row:
                    row = row.rstrip() + input_text + "\n"
                outfile.write(row)
    

