将多个结果保存到文件 Python
Saving to a file multiple results in Python
我在将多个内容保存到一个文件时遇到问题。我想将 for 循环中打印的所有内容保存到一个文件中。我会删除打印语句并保存到文件中。我正在阅读的文件大约有 10,000 个整数。我正在阅读的 .txt 文件如下。
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()
如果我理解正确的话:
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()
我在将多个内容保存到一个文件时遇到问题。我想将 for 循环中打印的所有内容保存到一个文件中。我会删除打印语句并保存到文件中。我正在阅读的文件大约有 10,000 个整数。我正在阅读的 .txt 文件如下。
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()
如果我理解正确的话:
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()