No such file or directory

Hello, i got komodo 11.1.1 and i have a problem. When i wrote simple code for file opening:

with open('file name') as file object:
    contents = file_object.read()
    print(contents)

Simple, isn’t it? This file and another one resides in one folder and i can’t understand why i got error as in topic? In addition, i got another interpretatior: Thony AND HE DOES THIS WORK CLEARLY, THE SAME CODE! I need your help, i like komodo design so much, that i dont want to leave it.

Hi @1111,

This question isn’t related to Komodo. This is a Python question so better suited to Stackoverflow. That’s just for future reference.

If you read the Python docs for the open() function you’ll see that you’re missing an optional argument for the mode to open the file in. If the arugment isn’t provided it defaults to r (aka. read) which requires that the file exist already. So unless you already have a file called “file name” on in the directory you’re running your script in then it will fail.

This should work:

with open('file name', 'w') as file object:
    contents = file_object.read()
    print(contents)

Note that opening a file in “write” mode truncates every time you re-open and write to it. w+ would append.

As a small nit, I’d avoid having spaces in your file names.

  • Carey

Thanks you a lot for your answer, but as I wrote I have a txt file in the same folder as my opening program. Also I understand, that im in read mode. I use different IDE and one is working and another(Komodo) not. I expected to see some hints about komodo settings.

@1111, Ahh I thought you were saying someone else, on a different computer ran your code and it worked. I see you meant a different program.

I see from your screenshot that you’re running the script using a toolbox run command so I’d assume the issue is from how you configured that.

Can you share a screenshot of the toolbox items configuration?

Actually, @1111, since you’re using Komodo IDE you have multiple better options than a toolbox Run Command. Either use Run in Line using Ctrl + B or “Run without debugger” by pressing F7.

  • Carey

You are absolutely right! If I start program with debugger, I got correct answer. Ctrl + and f7 don’t work on my computer. ( Ctrl + just zooming text). I was fighting with ‘run’ tool a lot of time and still don’t have sense about it.

@1111,

My guess, give the error that it can’t find the file, is that the Run Command Run in directory is wrong in the Advanced Options tab of the properties window. ie. the script is being run in the wrong “context” so it can’t see the relative path.

I just had a thought, you could have the script print the abspath of the relative path you’re using in the script with the following code:

import os
 import os
print(os.path.abspath("openme/pistol.txt")) #assuming you're still using that path in your script.

Put that before the with open code.