如何使用python检查文件中是否存在单独一行的数字

2024-06-26 13:28:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个档案PhaseMar.txt文件每一行只包含

4
16
14
44
55
34

它需要检查是否有一个特定的数字让我们假设16存在于该文件或没有。你知道吗

我正在使用

test_file = open('PhaseMar.txt', 'r')   #modification!
test_lines = test_file.readlines()  #modification!
print test_lines
size =len(test_lines) #[0]
print size
count=0
              for i in xrange(1,size):
               #print int(realID)
               #print int(test_lines[i])
               print (int(test_lines[i])-int(realID))
               if abs(int(test_lines[i])-int(realID))> 0.1:
                count=count+1
               else:
                count=0

               if (count>0):
                print "true" 
               else:
                print "false"
               count=0

它检查所有的条目6次,它给我的答案是真的,当数字存在。但是,它也会打印所有的错误。我想知道是否有一个班轮存在这个。 谨致问候


Tags: 文件testtxtsizeifcount数字else
1条回答
网友
1楼 · 发布于 2024-06-26 13:28:34

假设检查文件中的整数16PhaseMars.txt文件,如下所示的快速解决方案,但由于需要将整个文件读入内存,因此处理大文件的内存效率不高

check = str(16)
with open('PhaseMars.txt') as f:
    match = check in f.read().splitlines()
    # match will be True if match inside file, False otherwise

如果您需要处理大文件,itertools可能很方便,它只在每次迭代需要处理时读取文件中的每一行。你知道吗

例如,假设我们对16以上的数字感兴趣 导入itertools

chk = 16
with open(r'PhaseMars.txt') as f:
    # match holding iterator for line that match > 16 predicate
    # replace itertools.ifilter with just filter for python 3
    match = itertools.ifilter(lambda x:int(x.strip()) > chk, f)

    # you may process the match item afterwards 
    for i in match:
        # do your processing of the matching item here
        # for eg. just print them out
        print(i.strip())

    # OR built them into a list
    matchlist = list(match)

相关问题 更多 >