Hello all,

I am new to python programming and the Qs might seem stupid but i would really appreciate some help :-)

It is just a for loop that i want to use, but it doesnt seem to work properly.
I need to sort a file as per one of the column values and store them into different files which are named acc to the sorting criteria. I created a list and am using a loop to sort everything at one go.

The Loop works fine for the first cycle, but for the next cycles the output files are getting created but they are not getting populated. The first cycle creates, sorts and populates the output file.2

here is the code snippet

import sys
import os

#Get the type and path of the input file from the user
choice = raw_input("Please choose type of file you want to categorize")
inFile = raw_input("\nPlease Enter the complete path for the input file including the file extension \
(Ex: C:\Documents and Settings\...\Desktop\python\FILENAME.csv):")
inputFile = open(inFile, "r")

# Get the name of Coin from the user
coin = raw_input("\nPlease enter the Coin or COINS; seperated by space: according to which you want to categorize the file:")
coinNameforFile = coin.replace('/','_') #we need to replace '/' with '_' for using it in the name of the file
coinNameforFileList = coinNameforFile.split()
num = len(coinNameforFileList)
coinList = coin.split()
print coin
print coinNameforFile


[B]for i in range(0,num):[/B]
    #assign the name and path of the output file to be generated
    fileName = choice + coinNameforFileList[i]
    outFile = os.path.join("c:\\Documents and Settings\\Ashwin Kulkarni\\Desktop\\", "%s.csv" %fileName)
    print "\nYour Output File name is :: %s\n" %outFile

    #Open the output file for writing
    outputFile = open(outFile, "w")


   
        
    if choice == "abc":
        outputFile.write(" some text which prepopulates the files ")

        print " above text has been written to the file"

    if choice == "cde":
        outputFile.write("some text which prepopulates the files")

        print "above text has been written to the file"
        


    #######################################################################################
    #
    # Now that we have the Input and the output file ready, read the input file and
    # manipulate the file as per the users requirement.
    #
    #######################################################################################


    #start reading the input file line by line 
    inputFile.readline()
    #define a output array
    resultsList = []
        
    ########################################################################################
    # categorize the input file as per the choice made by the user.
    ########################################################################################
    if choice == "abc":
         for line in inputFile:
            line = line.rstrip() # Strip the cell Values of the trailing spaces
            fields = line.split(',') #Seperate the values in fields with a comma

            # Assign the fields present in the input file to fields
            a,b,c,d,e,f,g=fields
            #print fields

            for item in fields:
                if item == coinList[i]:
                        print item
                        resultsList = ([a,b,c,d,e,f "\n"])
                        #print resultsList

                        #Output the results in required format
                        outStr ='  '.join([''.join(item) for item in resultsList])

                        #write the results to the specified file
                        outputFile.write(outStr)

                        #print the output to standard output for review
                        print outStr

    

#clean close the input and output files
inputFile.close()
outputFile.close()

Recommended Answers

All 6 Replies

Please learn how to use code tags around your code, nobody will read the ugly mess you are presenting otherwise.

Please learn how to use code tags around your code, nobody will read the ugly mess you are presenting otherwise.

No problem, I just put everything together. Let me try doing it again.......

import sys
import os


choice = raw_input("Please choose type of file you want to categorize(abc, cde):")

inFile = raw_input("\nPlease Enter the complete path for the input file including the file extension")

inputFile = open(inFile, "r")

coin = raw_input("\nPlease enter the Coin or COINS; seperated by space: according to which you want to categorize the file:")

coinNameforFile = coin.replace('/','_')

coinNameforFileList = coinNameforFile.split()

num = len(coinNameforFileList)

coinList = coin.split()


[B]# This is where the problem starts[/B]
for i in range(0,num):
    
    fileName = choice + coinNameforFileList[i]
    
    outFile = os.path.join("c:\\Documents and Settings\\......\\Desktop\\", "%s.csv" %fileName)
    
    outputFile = open(outFile, "w")


    if choice == "abc":
        outputFile.write("# Node Export file by DS-TE Import/Export module \n# Locale is optional in import\
        and mandatory in export.\n locale : C \n# Router_Name, Router_Model, Longitude (X), Latitude (Y), Bw_Constraint_Model\n")

       
    if choice == "cde":
        outputFile.write("# Node Export file by DS-TE Import/Export module \n# Locale is optional in import\
        and mandatory in export.\n locale : C \n# Link_Name, Link_Model, Router_A, Router_B, Data_Rate, Direction\n")

        
   
    inputFile.readline()
   
    resultsList = []
        
   
    if choice == "LinkNode":
         for line in inputFile:
            line = line.rstrip() 
            fields = line.split(',') 

            Link_Name,Link_Model,Router_A,Router_B,Data_Rate,Direction,COIN=fields
            
            for item in fields:
                if item == coinList[i]:
                        print item
                        resultsList = ([Link_Name, ",", Link_Model,",", Router_A, ",", Router_B, ",", Data_Rate, ",", Direction, "\n"])
                        

                        outStr ='  '.join([''.join(item) for item in resultsList])

                        outputFile.write(outStr)

                        print outStr

    
    if choice == "CellSite":
        for line in inputFile:
            line = line.rstrip() # Strip the cell Values of the trailing spaces
            fields = line.split(',') #Seperate the values in fields with a comma

            CELL_NAME, SWITCH, SWITCH_NAME, LATITUDE_DEGREES, LONGITUDE_DEGREES, COINS=fields
            

            for item in fields:
                if item == coinList[i]:
                    print item
                    resultsList = ([CELL_NAME,",","umts_node_b",",",LONGITUDE_DEGREES,",", LATITUDE_DEGREES,"\n"])
                    
                    outStr ='  '.join([''.join(item) for item in resultsList])

                    outputFile.write(outStr)

                    print outStr
        

#clean close the input and output files
inputFile.close()
outputFile.close()

Let me know if this is readable !!!
As I said, am new to the whole programming domain and am unsure of which snippet to post.

No, put code tags around the code in your post eg.

#python code here [/code ][code ]
#python code here
[/code ]

Thnx for bearing with me !!! first time posting you see !!!!!!

Hope this is the right way to do it.

import sys
import os


choice = raw_input("Please choose type of file you want to categorize(abc, cde):")

inFile = raw_input("\nPlease Enter the complete path for the input file including the file extension")

inputFile = open(inFile, "r")

coin = raw_input("\nPlease enter the Coin or COINS; seperated by space: according to which you want to categorize the file:")

coinNameforFile = coin.replace('/','_')

coinNameforFileList = coinNameforFile.split()

num = len(coinNameforFileList)

coinList = coin.split()


# This is where the problem starts
for i in range(0,num):
    
    fileName = choice + coinNameforFileList[i]
    
    outFile = os.path.join("c:\\Docum....\\......\\Desktop\\", "%s.csv" %fileName)
    
    outputFile = open(outFile, "w")


    if choice == "abc":
        outputFile.write("# Node Export file by DS-TE Import/Export module\n")

       
    if choice == "cde":
        outputFile.write("# Node Export file by DS-TE Import/Export module \n")

        
   
    inputFile.readline()
   
    resultsList = []
        
   
    if choice == "LinkNode":
         for line in inputFile:
            line = line.rstrip() 
            fields = line.split(',') 

            Link_Name,Link_Model,Router_A,Router_B,Data_Rate,Direction,COIN=fields
            
            for item in fields:
                if item == coinList[i]:
                        print item
                        resultsList = ([Router_A, ",", Router_B, ",", Data_Rate, ",", Direction, "\n"])
                        

                        outStr ='  '.join([''.join(item) for item in resultsList])

                        outputFile.write(outStr)

                        print outStr

    
    if choice == "CellSite":
        for line in inputFile:
            line = line.rstrip() # Strip the cell Values of the trailing spaces
            fields = line.split(',') #Seperate the values in fields with a comma

            CELL_NAME, SWITCH, SWITCH_NAME, LONG, LAT, COINS=fields
            

            for item in fields:
                if item == coinList[i]:
                    print item
                    resultsList = ([CELL_NAME,",",LONGITUDE,",", LATITUDE_DEGREES,"\n"])
                    
                    outStr ='  '.join([''.join(item) for item in resultsList])

                    outputFile.write(outStr)

                    print outStr
        

#clean close the input and output files
inputFile.close()
outputFile.close()

There are some dangling lines in your code like:
Link_Name,Link_Model,Router_A,Router_B,Data_Rate,Direction,COIN=fields

or

CELL_NAME, SWITCH, SWITCH_NAME, LONG, LAT, COINS=fields

Are those comments? If yes, they need a # in front.

Actually no, They are not! its just that they are longer than the rest and so they continue on the next line without indentation

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.