Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.txt文件在Python 3.3.3中读写不正确_Python_File_Text_Python 3.x - Fatal编程技术网

.txt文件在Python 3.3.3中读写不正确

.txt文件在Python 3.3.3中读写不正确,python,file,text,python-3.x,Python,File,Text,Python 3.x,无论如何,我一直在尝试在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

无论如何,我一直在尝试在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',打印出从2到用户输入的素数的每个数字,顺序我还没有找到。

Ya,正如@maurelio79和@DSM所说,看起来您正在读取和写入同一个文件,并且正在向列表中添加int…这应该是不可能的。此外,使用with打开文件更为简洁:

pList = []
with open(fle_path, 'r') as fle:
   for line in fle:
      pList.append(int(line.rstrip("\n")))


#find and append new primes to pList using pList.append(<new prime>)


with open(fle_path, 'a') as fle: 
   for item in pList:
      fle.write(str(item)+"\n")
pList=[]
开放式(fle_路径,'r')作为fle:
对于fle中的行:
pList.append(int(line.rstrip(“\n”))
#使用pList.append()查找新素数并将其附加到pList
开放式(fle_路径,'a')作为fle:
对于pList中的项目:
fle.write(str(项目)+“\n”)
使用“r”读取文件,“w”每次以空白文件启动a,使用“a”附加到现有文件。您可以使用相同的文件,但可以使用'a'参数附加新找到的素数

当文件存在循环时,使用with语句会自动关闭文件。

我已经(大致)重写了您的示例,向您展示了哪些被认为是更好的习惯用法

首先,您的prime finder可能很棒,因为我只测试了一个数字:

def isprime(n):
    '''check if integer n is a prime'''
    # make sure n is a positive integer
    n = abs(int(n))
    # 0 and 1 are not primes
    if n < 2:
        return False
    # 2 is the only even prime number
    if n == 2: 
        return True    
    # all other even numbers are not primes
    if not n & 1: 
        return False
    # range starts with 3 and only needs to go up the squareroot of n
    # for all odd numbers
    for x in range(3, int(n**0.5)+1, 2):
        if n % x == 0:
            return False
    return True
最后,读入整数
2-end
文件,依次测试每个整数的素性。将素数写入新文件
prime.txt

with open('/tmp/nums.txt') as f, open('/tmp/primes.txt', 'w') as fout:
    for n in f:
        n=int(n)
        if isprime(n):
            print(n)
            fout.write('{}\n'.format(n))
如果您想要一个素数列表,下面是如何附加到列表中:

primes=[]        
with open('/tmp/nums.txt') as f:
    for n in f:
        n=int(n)
        if isprime(n):
            print(n)
            primes.append(n)
有几点需要注意:

  • 使用关键字打开文件。您的文件将在最后自动关闭
  • 该文件用作迭代器,因为在这种情况下没有理由将整个文件读入内存
  • 对于每一行回车符,无需执行
    int(line.strip())
    int
    首先去掉空白,这样
    int('12\r\n')
    工作正常
  • pList+(int(line.strip())
    可能是一个
    TypeError
    ,因为您无法将int连接到列表。改用
    pList.append(int(line))

    您的文件被擦除,因为您使用的是同一个文件,并且在编写新文件时使用的是“w”而不是“a”。这就是你想要的吗?我想这涵盖了一部分内容……但我主要是想找出我阅读'primes.txt'的方法一开始不起作用的原因。不过,谢谢!我甚至不知道这些代码是如何运行的。您正在将int添加到列表中--您不应该得到
    TypeError
    ?是:
    回溯(最近一次调用):文件“primes.py”,第5行,pList=pList+(int(line.strip()))TypeError:只能将列表(而不是“int”)连接到列表中
    with open('/tmp/nums.txt') as f, open('/tmp/primes.txt', 'w') as fout:
        for n in f:
            n=int(n)
            if isprime(n):
                print(n)
                fout.write('{}\n'.format(n))
    
    primes=[]        
    with open('/tmp/nums.txt') as f:
        for n in f:
            n=int(n)
            if isprime(n):
                print(n)
                primes.append(n)