Question : Reading a file.

Hi,

I have had this problem in python several times and i have no idea why.

I read geneidname.txt and i want to change the last word of each line from C to c. Well, my solution is bellow and it works but I have no idea why the new file prints until line 4886 instead of 4994!!!!!! I have had this problems several times reading python files and i have no idea why. Please tell me what's wrong, not only give me a solution.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
geneidnameF = open('geneidname.txt', 'rU')
geneidnamenewF = open('geneidnamenew.txt', 'w')
 
count = 1
for line in geneidnameF:
	if line[-2] == 'C':
		line = [ch for ch in line]
		line [-2] = 'c'
		line = ''.join(line)
	print count
	count = count + 1
	geneidnamenewF.write(line)
Open in New Window Select All

Answer : Reading a file.

... sorry I hit submit too soon.

Anyway, if the loop was exiting after 4886 lines -- in other words, if you ran your script and the last line printed was '4886' (from, 'print count'). Then you could add a print statement after the loop to inspect the contents of the last line read from the file ... something like ...

HTH
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
geneidnameF = open('geneidname.txt', 'rU')
geneidnamenewF = open('geneidnamenew.txt', 'w')
 
count = 1
for line in geneidnameF:
        if line[-2] == 'C':
                line = [ch for ch in line]
                line [-2] = 'c'
                line = ''.join(line)
        print count
        count = count + 1
        geneidnamenewF.write(line)
 
# past the loop 'line' will contain 
# the last line read from geneidnameF
print repr(line) # repr() will show \n and \r chars, etc.
 
geneidnameF.close()
# geneidnamenewF.flush()
geneidnamenewF.close()
Open in New Window Select All
Random Solutions  
 
programming4us programming4us