0

I have a socket that I am sending data to through a file created using the makefile method of a socket. However, the mode of the file created using makefile is 'wrb'.

I understand that 'w' = write, 'r' = read, and 'b' = binary. I also understand that you can combine them in a number of different ways, see Confused by python file mode "w+", which contains a list of possible combinations. However, I've never seen 'w' and 'r' together.

What is their behavior when together? For example, 'r+' allows reading and writing, and 'w+' does the same, except that it truncates the file beforehand. But what does 'wr' do?

Community
  • 1
  • 1
Amndeep7
  • 2,022
  • 4
  • 17
  • 26

1 Answers1

1

The description in the Python 2.x docs suggests you would be able to both read and write to the file without closing it.

However, the behavior is not so.

Example:

f = open('myfile', 'wr')
f.write('THIS IS A TEST')
f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 9] Bad file descriptor

It will write, however not read. If we open the file with the option reversed:

f = open('myfile', 'rw')
f.read()
f.write('THIS IS ALSO A TEST')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 9] Bad file descriptor

Observed behavior is that the open() function only takes the first character for file opening option, and disregards the rest except if it ends in a 'b', which would donate that it would be opened in binary mode.

pappad
  • 41
  • 3
  • I was able to duplicate the results that you posted on codingground, which looks like it's running Python 2.7.5 on Fedora 20; however, I was not able to do so on my personal work machine. Here I'm running Python 2.7.1 on Win7 and receiving a ValueError: "ValueError: Invalid mode ('wr')". The interesting thing is that I don't receive any sort of error when the file is generated from the socket like so: `socket_file = socket.makefile('wrb')'. According to the docs, makefile returns a file object like any other file, so shouldn't it fail in this case like any other file? – Amndeep7 May 08 '15 at 21:03
  • I'm not sure. The most logical thing to do would be to update your python interpreter to the most recent supported version in the 2.x series, which looks to be 2.7.6; on my machine. Also I'm not familiar with how Windows handles python libraries, or any platform specific issues that may arise from using Windows. – pappad May 09 '15 at 03:56