【问题标题】:.txt File Not Reading and Writing Correctly in Python 3.3.3.txt 文件在 Python 3.3.3 中无法正确读写
【发布时间】: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 &lt;module&gt; pList=pList+(int(line.strip())) TypeError: can only concatenate list (not "int") to list

标签: python file text python-3.x


【解决方案1】:

是的,正如@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")

使用'r'读取文件,'w'每次都以空白文件开头,使用'a'附加到现有文件。您可以使用相同的文件,但使用 'a' 参数来附加新发现的素数。

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

【讨论】:

    【解决方案2】:

    我已经(大致)重写了您的示例,以向您展示什么被认为是更好的习语。

    首先,您的主要查找器可能很棒,因为我使用了一个基于仅测试一个数字的查找器:

    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
    

    接下来,我不知道你的源文件中有什么。在这里,我只是向您提出了“多远”的相同问题,然后展示了读取和写入该文件的更好方法:

    print('Hello and Welcome to the Prime Finder 000!')
    end=int(input('What integer would you like me to go to today?'))
    
    with open('/tmp/nums.txt', 'w') as fout:
        for n in range(1,end+1):
            fout.write('{}\n'.format(n))
    

    最后,读取整数文件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)
    

    注意几点:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 2017-01-03
      • 2016-05-12
      • 1970-01-01
      相关资源
      最近更新 更多