Select to view content in your preferred language

Why is my IF statement being ignored?

2992
3
03-01-2011 01:38 AM
LeeMusto
Emerging Contributor
I'm sure there is a simple answer, but it seems to be beyond my limited Python knowledge. I have some very large text files, in which data is arranged in columns. One of the attributes is 'Month' and I want to create a new txt file for each month. My code is as follows:

infile = open(r"P:\Months_Test.txt")

mth = 1

for inlines in infile.readlines():
    if str(mth) in inlines[-2:]:
       outfile = open(r"P:\Month_" + str(mth) + ".txt", 'a')
       outfile.write(inlines)
       outfile.close()
    else:
       mth += 1

infile.close()


If I run this code without the ELSE statement, it correctly outputs the month 1 data into the month 1 text file. However, as soon as I add the ELSE statement, it skips the IF statement completely and just counts the number of lines in the text file (I checked by printing mth). What am I doing wrong?
Tags (2)
0 Kudos
3 Replies
LeeMusto
Emerging Contributor
OK - just realised I should use 'For mth in range(1,13):' to solve problem. But, would still like to know why the IF statement wasn't working.

Also, why does this work:

'if str(mth) in inlines[-2:]:'

but, this doesn't:

'if str(mth) == inlines[-2:]' (Returns nothing)

The 'in' function will work if there are only 9 months, but runs into trouble for months 10-12.
0 Kudos
LoganPugh
Frequent Contributor
For pure Python questions I recommend StackOverflow.com. You will generally get answers within minutes of asking a question. This forum is more for ArcGIS-specific Python usage and is far less trafficked than SO.

In regards to your question I can only suggest to step through it in a debugger or sprinkle it with print statements so you are aware of the flow of control and variable contents at any point during execution.
0 Kudos
JasonScheirer
Esri Alum
When you iterate over a file, each line gives you the final return at the end, you'll need to do something like this:

if str(mth) in inlines.rstrip()[-2:]

Otherwise line[-2:] is equal to "\r\n" and not your number (which is at [-4:-2])
0 Kudos