正在读取txt结果0,但有个条目

2024-10-03 17:27:36 发布

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

奇怪的问题,我找不到问题。下面的代码将过滤后的条目复制到一个新的txt文件中,并应打印条目数,即_iphone.txt文件文件结尾包含(行)。你知道吗

结果总是0。但是,当我打开txt时,它包含条目。你知道吗

我错过什么了吗?你知道吗

term = "iphone"
file = open(./export/importlist.txt')
extoutput = open('./export/only_iphone.txt', 'w')
for line in file:
    line.strip().split(',')
    if term in line and 'samsung' not in line and 'htc' not in line:
        #print line
        extoutput.write('{}'.format(line))
file.close()
time.sleep(1)


numberofentries = 0

with open('./export/only_iphone.txt') as f:
    for line in f:
        if line.strip():
            numberofentries += 1

    print (numberofentries)

Tags: 文件intxtonlyforline条目export
2条回答

要继续Gabriel的回答,最好使用with open方式打开文件。所以你不能忘记关闭它,就像你在代码的第二部分所做的那样。你知道吗

term = "iphone"
with open('./export/importlist.txt') as my_file:
    with open('./export/only_iphone.txt', 'w') as extoutput:
        for line in my_file:
            line = line.strip().split(',')
            if term in line and 'samsung' not in line and 'htc' not in line:
                #print line
                extoutput.write('{}'.format(line))

time.sleep(1)


numberofentries = 0

with open('./export/only_iphone.txt') as f:
    for line in f:
        if line.strip():
            numberofentries += 1

    print (numberofentries)

你忘了关闭输出文件

term = "iphone"
file = open('./export/importlist.txt')
extoutput = open('./export/only_iphone.txt', 'w')
for line in file:
    line = line.strip().split(',')
    if term in line and 'samsung' not in line and 'htc' not in line:
        #print line
        extoutput.write('{}'.format(line))
file.close()
extoutput.close()

time.sleep(1)


numberofentries = 0

with open('./export/only_iphone.txt') as f:
    for line in f:
        if line.strip():
            numberofentries += 1

    print (numberofentries)

相关问题 更多 >