Python中的“IOError:[Errno 0] Error”错误

时间:2013-10-09 21:30:47

标签: python regex runtime-error

我有一个脚本应该附加到文件中,但它引发了一个我不理解的错误,并且不确定它是如何被触发的。

以下是代码:

import re

num_words = "four kiddiewinks|four children|four kids"
words_list = num_words.split('|')

def append_2synonym(words_list, num_words):
    with open('test2 words.txt', 'a+') as f:
        read_f = f.read()
        patt = r'^' + words_list[0] + '\|'
        result = re.search(patt, read_f, re.MULTILINE)
        if result == None:
            f.write("\n" + num_words)
        else:
            print "\nNo match found in '2 words.txt' file"

append_2synonym(words_list, num_words)

以下是'test2 words.txt'文件的内容:

five kiddiewinks|five kids|five children
mobile phone|cell phone|cellular phone
stinky cheese|smelly cheese

以下是我收到的完整错误:

Traceback (most recent call last):
  File "D:\Magic Briefcase\My Python Scripts\Spin Scripts\synonyms\testing2.py", line 16, in <module>
    append_2synonym(words_list, num_words)
  File "D:\Magic Briefcase\My Python Scripts\Spin Scripts\synonyms\testing2.py", line 12, in append_2synonym
    f.write("\n" + num_words)
IOError: [Errno 0] Error
[Finished in 0.1s with exit code 1]

1 个答案:

答案 0 :(得分:9)

Python file operations引用回答,当在Windows上进行读写切换时,必须有干预fflush,fsetpos,fseek或倒带操作。

这是一个可能的解决方法:

import re

num_words = "four kiddiewinks|four children|four kids"
words_list = num_words.split('|')

def append_2synonym(words_list, num_words):
    with open('test2 words.txt', 'a+') as f:
        read_f = f.read()
        patt = r'^' + words_list[0] + '\|'
        result = re.search(patt, read_f, re.MULTILINE)
        if result == None:
            f.seek(0,2) # change is here !!
            f.write("\n" + num_words)
        else:
            print "\nNo match found in '2 words.txt' file"

append_2synonym(words_list, num_words)

f.seek(0,2)中,2from_what参数。 from_what的{​​{1}}值从文件开头开始计算,0使用当前文件位置,1使用文件末尾作为参考点。 2可以省略,默认为from_what,使用文件的开头作为参考点。