2016-03-02 46 views
0

我在保存多个文件时遇到问题。我想将所有正在打印的for循环保存到文件中。我会删除打印语句并保存到文件中。我正在阅读的文件大约有10,000个整数。我正在阅读的.txt文件如下。在Python中保存多个结果

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() 

回答

0

如果我理解正确:

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() 
+0

你需要多一点的逻辑把前者'print'参数为一个字符串。或者,您可以将'file = file'作为关键字参数传递给'print',而不是使用'file.write'。 – Blckknght

+0

我只是删除了[i] hashed = hashing(bucket [i],data),它工作。感谢您的帮助 –

相关问题