Search code examples
python-3.xfile-writing

Saving to a file multiple results in Python


I am having problems saving multiple things to a file. I would like to save everything being printed in the for loop to a file. I would the remove the print statement and just save to the file. The file I am reading in is around 10,000 integers. The .txt file I am reading in is below.

http://nyx.net/~bcohen/CS2050/hw3a.txt

def hashing(buck, file):
    y = len(file) 
    size = int(y/buck)      # Size of Buckets
    nums = file
    lst = [set([]) for i in range(buck)]
    for i in range(y):
        z = nums[i] % buck
        val = nums[i]
        lst[z].add(val)

    return lst

#*******************************************************************

def reading():
    filename = input("What is the file name ")
    file = open(filename, "r")
    int_list = []
    for i in file.read().split():
        int_list.append(int(i))    

    return int_list 

#*******************************************************************
data = reading()
print("The file has ",len(data),"Elements")
buckets = int(input("How many buckets will be used? "))
hashed = hashing(buckets,data)

for i in range(buckets):
    print("Size of bucket #",i,"is equal to ",len(hashed[i]))


#file = open("Results.txt", "w")

#file.write()

#file.close()

Solution

  • If I understand correctly:

    file = open("Results.txt", "w")
    for i in range(buckets):
        hashed = hashing(buckets[i],data)
        file.write("Size of bucket #" + str(i) + "is equal to " + str(len(hashed[i])) + '\n')
    
    file.close()