Changing a file line - Python
Question: I've a file entitled **'users.txt'** with the following structure;
`username:info_about_the_user.`

Something like this:

**users.txt:**

> mark:stuffabouthim  
>  anthony:stuffabouthim  
>  peter:stuffabouthim  
>  peterpeter:stuffabouthim  
>  peterpeterpeter:stuffabouthim  
>  peterpeterpeterpeter:stuffabouthim  
>

The following part of the script needs to change a line (change info about an
user) but I'm having problems when the string is duplicated (peter -
peterpeter) and I dont know how to fix it.

    
    
    def test():
        fn = 'users.txt'
        f = open(fn)
        output = []
        changeuser = 'peterpeter'
        userinfo = 'HeIsTall'
        for line in f:
            if not changeuser+":" in line:
                output.append(line)
        f.close()
        f = open(fn, 'w')
        f.writelines(output)
        f.close()
        f = open("users.txt", "a")
        f.write(changeuser + ":" + userinfo+"\n")
        f = open("users.txt", "a")
    
    test()
    

This is the input I have:

**Input: users.txt:**

> mark:stuffabouthim  
>  anthony:stuffabouthim  
>  peter:stuffabouthim  
>  **peterpeter:HesAwesome**  
>  peterpeterpeter:stuffabouthim  
>  peterpeterpeterpeter:stuffabouthim  
>

I want to change info about peterpeter and have the following output:

**Output I want to have: users.txt:**

> mark:stuffabouthim  
>  anthony:stuff about him  
>  peter:stuffabouthim  
>  **peterpeter:HeIsTall**  
>  peterpeterpeter:stuffabouthim  
>  peterpeterpeterpeter:stuffabouthim  
>

But this is the input I'm having. All the lines behind peterpeter are getting
deleted among other things.

> mark:stuffabouthim  
>  anthony:stuffabouthim  
>  peter:stuffabouthim  
>  peterpeter:HeIsTall  
>

Can anyone give me a help with the code below to have the desired output?
Thanks.


Answer: You can have it the easy way with the
[`fileinput`](http://docs.python.org/library/fileinput.html) module:

    
    
    import fileinput
    
    def test():
        fn = 'users.txt'
    
        changeuser = 'peterpeter'
        newinfo = 'HeIsTall'
    
        for line in fileinput.input(fn, inplace=1):
            user, oldinfo = line.split(':')
            print '%s:%s' % (user, newinfo if user == changeuser else oldinfo.replace('\n', ''))
    
    if __name__ == "__main__":
        test()
    

