Python - 从函数中的文本文件中读取数字

时间:2014-12-30 12:56:53

标签: python file-io

我正在尝试编写一个程序,确保在文本文件上写入查找给定数字和限制之间的素数。如果该号码存在于文件中,它会尝试写入另一个与给定(输入)号码相互作用的号码。然后它写在文本文件上。 我的问题是检查文本文件中的数字是否存在。我怎么写呢?所以,我从早上开始研究,但是我找不到有用的答案。我认为Python的改变很有效。

示例:输入的数字为12,限制为3

生成的数字是1,5,7

第二次运行1,5,7存在于文本文件中,而不是生成11,13,17并打印它们。

def coprime(x,y):
    """Returns True if the number is copime
    else False."""
    if x % y == 0:
        return False
    else:
        return True


"""

def text_file() function will be here
if number searching number exists on the text file return True
else return False


"""

f = open("numbers.txt","a+")
i = 0
j = 0

num = int(raw_input("Please enter number "))
limit = int(raw_input("Please enter limit "))

while i < limit:
    if text_check(file,j) == False and coprime(num,j) == True:
        f.write(str(j))
        i += 1
        j += 1
        print "%d is written on the text file" % j 

    else:
        j += 1

f.close()

1 个答案:

答案 0 :(得分:1)

假设所有的名字都在不同的行上,如下所示:

1
5
7



from fractions import gcd

def coprime(n1, n2):
    return gcd(n1, n2) == 1 # same as if gcd(n1, n2) == 1:return True else: return False



with open("out.txt","a+") as f: # with automatically closes your files
    # add all previous numbers into a set, casting to int using map 
    # map(int, f)  equivalent to [int(ele) for ele in f] in python2
    nums_set = set(map(int, f)) # with 1 5 and 7 in the file nums_set = set([1, 5, 7])
    i = 0
    j = 0

    num = int(raw_input("Please enter number "))
    limit = int(raw_input("Please enter limit "))

    while i < limit:
        if j not in nums_set and coprime(num,j):
            f.write("{}\n".format(j))
            print "{} is written on the text file.".format(j)
            i += 1
            j += 1
            # add current j's from this run to the set to avoid reopening and rechecking he file        
            nums_set.add(j)       
        else:
            j += 1