I need the output of the following code to be printed in a text file. So far it creates the text file, but it does not print anything in it. Any help would be appreciated.

def findSlope (x1, y1, x2, y2):
    rise = y2 - y1
    run = x2 - x1
    if run == 0:
        slope = "undefined"
    else:
        slope = rise/run
    return slope

import sys, string

inFile = open("C:\Python\coordinates1.txt", "r")
outFile = open("exercise1.txt", "w")
lines = inFile.readlines()

for i in inFile:    
    origin = i.split(',')
    j=0
    for j in range(len(origin)):
        origin[j] = str.strip(str(origin[j]), "\n")

    inFile2 =  open("C:\Python\coordinates1.txt", "r")
    outFile2 = open("exercise1.txt", "w")
    outFile2.write(str)
    outFile2.close()
    print
    
    for k in inFile2:
        if k!=i:
            destination = k.split(',')
            e=0
            for e in range(len(destination)):
                destination[e] = str.strip(str(destination[e]), "\n")
                print origin
                print destination
                print findSlope(int(origin[1]), int(destination[1]), int(origin[2]), int(destination[2]))
    inFile2.close()
    outFile2.close()
                
inFile.close()
outFile.close()

Recommended Answers

All 2 Replies

You already open("exercise1.txt", "w") outside your loop. This creates a new empty file. Good. But you also open the same file in your for loop. Don't do that. Repeating the open statement in 'w' mode for that file recreates the empty output file each time it reads a line from your input file, thus erasing any content you have written to it.

You already open("exercise1.txt", "w") outside your loop. This creates a new empty file. Good. But you also open the same file in your for loop. Don't do that. Repeating the open statement in 'w' mode for that file recreates the empty output file each time it reads a line from your input file, thus erasing any content you have written to it.

There are other issues. After inFile.readlines() at line 14, the file position is at the end of the file, so the for i in inFile iterates over nothing: the loop's body is never executed.

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.