I am trying to write a python script to open file, read each line, and replace the 18th position of each line with a a user specified character (sysargv[3]) IF AND ONLY IF that 18th position is another user specified character (sysargv[2]). It should then save it as a file "renamed" For some reason Python runs amok. In some instances it renames every occurence of the user specified character regardless of position then in other lines it does not rename any of them, even if they are at position 18. My code is below. I can not find anything wrong with it. Can anyone see why Python might be misinterpreting my instructions so much?

#!/usr/bin/python



import sys



bh = "renamed" + sys.argv[1]



wh = sys.argv[2]



xc = sys.argv[3]



dh = open(sys.argv[1])



nh = open(bh,'w')





for line in dh:

    if line[17:18] == wh :

        line = line[17:18].replace(wh, xc)

        nline = nh.write(line)

        print line

    else : nline = nh.write(line)







dh.close()

A small test code:

line = 'abcdefghijklmnopqrstuvwxyz'

print line
print line[17]

if line[17] == 'r':
    line = line[0:17] + 'R' + line[18:len(line)]

print line

'''result >>
abcdefghijklmnopqrstuvwxyz
r
abcdefghijklmnopqRstuvwxyz
'''

nh[17:18] is list slice, not character. nh[17] is 18th character. I do not also find the meaning of your variables intuitive or line spacing reasonable.

I agree with pyTony. In addition, in your script you are replacing the entire line with sys.argv[3] when sys.argv[2] is encountered.

Hi all,
The spacing between lines that is in my message above is not the actual spacing that I used in my code. I guess that happened during pasting. Theres not really any particular rhyme or reason to how I named the variables, maybe their names could be changed to be more related to the values that they are actually representing. I have since been able to fix this script to do what I want it to, but I had to change a lot more than I thought I would and probably the way that I did it was not the most efficient (code parsimonious way).

This article has been dead for over six months. Start a new discussion instead.