【发布时间】:2014-01-23 00:19:10
【问题描述】:
无论如何,我一直在尝试在 Python 3.3.3 中读取和写入文本文件,但它一直没有工作。我的代码如下:
import math
pFile=open('/Users/Username/Desktop/Programming:Design/Program Access Files/primes.txt')
pList=[]
for line in pFile:
pList=pList+(int(line.strip()))
def testPrime(num,pList):
if num<=1:
return False
testList=[]
place=0
sqrt=math.sqrt(num)-((math.sqrt(num))%1)
p=pList[place]
while p<=sqrt:
testList.append(p)
place=place+1
p=pList[place]
for i in testList:
if i%num==0:
return False
return True
print('Hello and Welcome to the Prime Finder 000!')
end=int(input('What integer would you like me to go to today?'))
for j in range(pList[-1],end+1):
if testPrime(j,pList)==True:
pList.append(j)
print(j)
pFile.close()
pFile=open('/Users/Username/Desktop/Programming:Design/Program Access Files/primes.txt','w')
for k in pList:
pFile.write(str(k))
pFile.write('\r\n')
pFile.close()
这个程序应该搜索所有正整数以找到素数。我试图存储找到的素数的文本文件是“primes.txt”,在我尝试打开它时显示的目录中。但是,我读取文件的方法一定有问题,即:
pFile=open('/Users/Username/Desktop/Programming:Design/Program Access Files/primes.txt')
pList=[]
for line in pFile:
pList=pList+(int(line.strip()))
我确信我的查找素数的功能有效,但它们没有正确存储。目前,该程序所做的是擦除文本文件“primes.txt”并以我尚未找到的顺序打印出从 2 到用户输入的数字作为素数的每个数字。
【问题讨论】:
-
您的文件已被擦除,因为您使用的是同一个文件,并且当您编写新文件时,您使用的是 'w' 而不是 'a'。这是你想要的吗?
-
我认为这涵盖了一些内容……但主要是我在寻找我阅读“primes.txt”的方法一开始就不起作用的原因。不过谢谢!
-
我看不出该代码是如何运行的。您正在向列表中添加一个 int - 您不应该得到一个
TypeError吗? -
是:
Traceback (most recent call last): File "primes.py", line 5, in <module> pList=pList+(int(line.strip())) TypeError: can only concatenate list (not "int") to list
标签: python file text python-3.x