Skip to content

python中的file重用错误

Shuang0420 edited this page May 31, 2016 · 1 revision

错误代码:

f = open('test', 'r')
output = open('output.seq', 'w')
count = len(f.readlines())
print count

# read file and separate words
for line in f:
    line=line.strip('\n')
    seg_list = jieba.cut(line)
    output.write(' '.join(seg_list) + '\n')

错误:

打印count,但是不会写入文件

解决:

重新打开或者是保存文件内容

f = open('test', 'r')
output = open('output.seq', 'w')
input=f.readlines()
count = len(input)
print count

# read file and separate words
for line in input:
    line=line.strip('\n')
    seg_list = jieba.cut(line)
    output.write(' '.join(seg_list) + '\n')

其它

并不知道如何解释原因,因此姑且称这种现象为file不能重用问题,同样的,当我们试图两次去读取文件时,第二次并不会读到,如下代码。所以尽量可以避免这种写法,用readlines实现文件内容的读取。

f = open('test', 'r')
for line in f:
    print line
for line in f:
    print line

[[TOC]]

Clone this wiki locally