“IOError: [Errno 0] 错误";Python中的错误 [英] "IOError: [Errno 0] Error" error in Python

查看:219
本文介绍了“IOError: [Errno 0] 错误";Python中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a script that should append something to a file, but it is raising an error that I don't understand and not sure how it is being triggered.

代码如下:

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'文件的内容:

Here is the contents of the 'test2 words.txt' file:

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

这是我得到的完整错误:

Here is the full error I am getting:

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]

推荐答案

引用 Python 文件操作、在Windows上进行读写切换时,必须有中间的fflush、fsetpos、fseek或rewind操作.

Quoting answer from Python file operations, when switching between reading and writing on Windows, there must be an intervening fflush, fsetpos, fseek, or rewind operation.

这是一个可能的修复:

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 参数.0from_what 值从文件的开头开始度量,1 使用当前文件位置,2使用文件的结尾作为参考点.from_what 可以省略,默认为0,以文件开头为参考点.

In f.seek(0,2), 2 is the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.

这篇关于“IOError: [Errno 0] 错误";Python中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆