Error "IOError: [Errno 0]" in Python

I have a script that should add something to a file, but it causes an error that I don’t understand and don’t know how it starts.

Here is the code:

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) 

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

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

Here is the complete error I get:

 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] 
+7
source share
1 answer

Quoting the answer from File operations in Python , when switching between reading and writing on Windows, the intermediate operation fflush, fsetpos, fseek, or rewind should be performed.

Here is a possible fix:

 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) 

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

+8
source

Source: https://habr.com/ru/post/955627/


All Articles