How to write data results into an output file in python
<p>I have wrote this code to analyze and search geological coordinates for proximity of data points. Since I had so many data points, the output in PyCharm was becoming overloaded and gave me a bunch of nonsense. Since then I have worked to try and solve this issue by writing the True/False results into separate documents on my computer. </p>

<p>The point of this code is to analyze the proximity of coordinates in file1 to all elements in file2. Then return any resulting matches of coordinates which share proximity. As you will see below I wrote a nested for loop to do this which I understand may be a sort of brute force tactic so if anybody has a more elegant solution them I would be happy to learn more. </p>

<pre><code>import numpy as np
import math as ma

filename1 = "C:\Users\Justin\Desktop\file1.data"
data1 = np.genfromtxt(filename1,
                     skip_header=1,
                     usecols=(0, 1))
                     #dtype=[
                            #("x1", "f9"),
                         #("y1", "f9")])
#print "data1", data1

filename2 = "C:\Users\Justin\Desktop\file2.data"
data2 = np.genfromtxt(filename2,
                      skip_header=1,
                      usecols=(0, 1))
                      #dtype=[
                             #("x2", "f9"),
                             #("y2", "f9")])

#print "data2",data2

def d(a,b):
    d = ma.acos(ma.sin(ma.radians(a[1]))*ma.sin(ma.radians(b[1]))
                +ma.cos(ma.radians(a[1]))*ma.cos(ma.radians(b[1]))*       (ma.cos(ma.radians((a[0]-b[0])))))
    return d

results = open("results.txt", "w")

for coor1 in data1:
    for coor2 in data2:
        n=0
        a = [coor1[0], coor1[1]]
        b = [coor2[0], coor2[1]]
        #print "a", a
        #print "b", b

    if d(a, b) &lt; 0.07865:  # if true what happens
        results.write("\t".join([str(coor1), str(coor2), "True", str(d)]) + "\n")

    else:
        results.write("\t".join([str(coor1), str(coor2), "False", str(d)]) + "\n")
results.close() 
</code></pre>

<p>This is the error message I get when I run the code: </p>

<p><code>results.write("\t".join([str(coor1), str(coor2), "False", str(d)]) + "\n")
ValueError: I/O operation on closed file</code></p>

<p>I think my problem is that I don't understand how I am supposed to write, save and organize the files in a meaningful format into my computer. So, again if anybody has any advice or suggestions I would be very grateful for the support!</p>

<p>My suggestion: take your code that writes to the file and wrap it in a context manager. E.g. <a href="https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/" rel="nofollow">https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/</a></p>

python geolocation coordinates pycharm data-analysis