正確輸入反正,我一直在試圖讀取和寫入在Python 3.3.3一個文本文件,它一直沒有工作。我的代碼如下:.txt文件無法讀取,並在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'寫入新文件時。這是你想要的嗎? – maurelio79
我認爲它涵蓋了一點...但主要是我正在尋找一個原因,爲什麼我的閱讀'primes.txt'的方法不起作用。不過謝謝! – PythonDabbler
我看不到代碼甚至可以運行。你正在向列表中添加一個int - 你不應該得到一個'TypeError'嗎? – DSM