2/9 the open() function

I DID get the right answer.

class Point3D(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
    return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print my_point

what i want to know is why everything fed to open() must be in string form?

1 Like

Hi, @benley_maniac,

The code you posted applies to a different exercise from the one that presents the open function.

To open a file, you must supply the file name. It must be a string, however, you can use a variable or other expression to supply that name, if you want, provided that the value represents a valid file name. The mode must also be a string, but again, it can be any expression that resolves to a valid mode.

ok, maybe I didn’t get the right answer…

actually, I probably just pasted the wrong code. :slight_smile:

but the question was why in STRING form, when every other function can accept any form (except for type specific functions of course) IE, this is the only function I know of where you have to CHANGE everything into a string, even things that are not strings.

What am I doing wrong? I am getting th error:

Traceback (most recent call last):
File “python”, line 1, in
IOError: [Errno 2] No such file or directory: ‘output.txt’

Here is my code:

my_file = open("output.txt", "r+")

A teacher came to help me, so now it’s solved, but I still don’t know why it doesn’t work:

my_file = open("output.txt", "w")
my_file = open("output.txt", "r+")

Why do you have to open the file with “w” mode before doing it with “r+” mode ?

1 Like

I believe that’s because when you open a file in Python with “w” or “a”, it will create the file if it doesn’t exist. “r” only reads the file in the working directory - it will not create the file if it doesn’t exist. The problem with this section is likely because they don’t have the file existing in the working directory.

1 Like

In the hint , it says “r+” is write and read mode.
So ‘r+’ mode can write but still can not create a file?

1 Like

I’m confused by this as well. ‘w’ just writes the file, so ‘r+’ should do what ‘w’ does in addition to the read feature.

Is this a bug? Seems like r+ would’ve been enough to complete the exercise. The lesson doesn’t say all these exercises have to begin with the ‘w’ line of code.

1 Like

The solution is simply to open the file in the write mode (“w”) and then open it in the read mode(“r”), I have no idea why this should be done but at least it works for me.

1 Like

@javapro67515 your code works for me. But still I’m confused why I have to use the “W” function as it was not in the instruction. But thanks for your code.

Happy Coding :slight_smile:

1 Like

ive tried it now without the opening output “r+” and it works!
my_file = open(“output.txt”, “r+”)