3

I am using python 3.5.2 interpreter in a Windows 10 environment.

I entered the following lines according to the Google's Python Course:

>>> import sys,os,codecs
>>> f=codecs.open('foo.txt','rU','utf-8')
>>> for line in f:
...    f.write('£ $')
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Users\rschostag\AppData\Local\Programs\Python\Python35-32\lib\codecs.py", line 718, in write
    return self.writer.write(data)
  File "C:\Users\rschostag\AppData\Local\Programs\Python\Python35-32\lib\codecs.py", line 377, in write
    self.stream.write(data)
io.UnsupportedOperation: writ

The contents of foo.txt are currently:

string1
string2

foo.txt, according to Save As... in Notepad, is ANSI. Does this need to be converted to UTF-8 in order to write UTF-8 characters to the file?

host_255
  • 361
  • 2
  • 7
  • 18

1 Answers1

6

You have the file open for reading, not writing. Hence, the unsupported operation. You can't write to a file opened for reading.

The rU specified reading

f=codecs.open('foo.txt','rU','utf-8')

To open for writing:

f=codecs.open('foo.txt','w','utf-8')
sytech
  • 29,298
  • 3
  • 45
  • 86