这里是附加信息:
问题似乎与 prime.append(row) 以及 csv.reader 如何从 csv 文件中提取信息有关。
当我在记事本中打开 csv 文件时,文件为:
2
3
5
当我第一次编写程序时,我让它将所有内容发布到一个文本文件中,并用逗号分隔。大约 5000 万,线路变得太长,它崩溃了。我正在尝试重写程序以发布到 csv 并垂直附加数字(如记事本示例中)
这是我目前拥有的完整程序:
#!/bin/python3
import time
import os
import csv
i=1
candidate=5
startRows = (2,3,5)
prime = []
folderLocation = "c:/notNow/"
primeName = "primeNumbers.csv"
primePath=folderLocation + primeName
#check to see if the destination folder has been created
if os.path.isdir(folderLocation) is False:
# if false, create the folder
os.makedirs(folderLocation)
print ("The directory was created")
else:
print ("The directory exists")
# check to see if the prime file has been created
if os.path.isfile(primePath) is True:
# if the prime file exists, load it
# candidate will retain the highest value
# and that's where the testing will start
with open(os.path.join(primePath), newline='') as add2list:
hold = csv.reader (add2list, delimiter=',')
for row in hold:
# remove the outer section of brackets from the csv input
row="".join(row)
prime.append(row)
candidate=prime[-1]
print ("The csv file was loaded")
print ("The list consists of:", prime)
print ("The highest prime is", candidate)
time.sleep(1)
else:
# Create and populate the prime file
f = open(primePath, "w", newline = '')
writer = csv.writer(f)
for x in startRows:
writer.writerow([x])
prime.append(x)
print ("The file was created and populated")
candidate=prime[-1]
print ("The highest prime is", candidate)
time.sleep(1)
candidate = prime[-2]
print ("The list consists of:", prime )
time.sleep(1)
while i > 0:
i = 1
x = "True"
print ("this has been reset")
print ("i=",i)
print ("x=",x)
print ("end of reset message")
print ("")
time.sleep(1)
while x=="True":
print ("candidate is", candidate)
print ("prime to test is", prime[i])
time.sleep(1)
print(candidate,"/", prime[i],"=",candidate%prime[i])
# % (aka modulo) returns the remainder from a division
if candidate%prime[i] == 0:
print ("candidate is not prime -->", candidate)
candidate+=2
x = "False"
# increment the counter
i+=1
# test for end of the array
# if this is the end of the array then candidate is prime
try:
test=prime[i]
# open the file in append mode
except:
with open(os.path.join(primePath), "a") as add2file:
csv_writer = writer(add2file)
csv_writer.writerow(str(candidate))
print ("PRIME IDENTIFIED --->", candidate)
prime.append(candidate)
print("ARRAY HAS BEEN UPDATED WITH", candidate)
x="False"
candidate+=2
当我运行它时,我得到以下输出:
The directory exists
The csv file was loaded
The list consists of: ['2', '3', '5']
The highest prime is 5
this has been reset
i= 1
x= True
end of reset message
candidate is 5
prime to test is 3
Traceback (most recent call last):
File ".\primeNumberTest.py", line 86, in <module>
print(candidate,"/", prime[i],"=",candidate%prime[i])
TypeError: not all arguments converted during string formatting
感谢您的关注和帮助。我认识到代码中可能存在其他问题。我很高兴/愿意自己解决这些问题。我似乎无法弄清楚这个问题,因为正在输入的数据无法使用。