0
def generate_log(dirname, log_object):
    print(os.path.dirname(__file__),'dfsdfds')
    print(os.listdir())
    for smell in log_object:  
        log = open("../../output/logs/{}_logs".format(smell), "w")
        for elem in log_object[smell]:
            log.write('filename: {}, smelly_lines: {}, metric: {}\n'.format(elem['filename'], str(elem['lineno']), str(elem['metric'])))

My function tries to write some logs in to the directory output/logs/ The directory that I am calling this function is C:\Users\user\Desktop\proj\src\Detector. Since I want the output directory to be generated in /proj which is my project root, I thought doing ../../ would work, but it gives me

log = open("../../output/logs/{}_logs".format(smell), "w") FileNotFoundError: [Errno 2] No such file or directory: '../../output/logs/long_method_logs'

Is there anything I can do to fix this?

martineau
  • 119,623
  • 25
  • 170
  • 301
Dawn17
  • 7,825
  • 16
  • 57
  • 118

1 Answers1

2

You should use the os module with its submodule os.path

For joining a paths you should do os.path.join(path1, path2)

In your case you should do something like this:

log = open(os.path.join(os.pardir, os.pardir, "output", "logs", "{}_logs").format(smell), "w")

Also you should close this file via log.close() before exit

And for this purposes there is a logging module

sakost
  • 250
  • 4
  • 15
  • Thanks for the answer, but I am still getting this: `log = open(os.path.join(os.pardir, os.pardir, "output", "logs", "{}_logs").format(smell), "w") FileNotFoundError: [Errno 2] No such file or directory: '..\\..\\output\\logs\\long_method_logs' ` – Dawn17 Apr 24 '19 at 22:10
  • @Dawn17 may be there are not such directories at paths that you showed us – sakost Apr 24 '19 at 22:13
  • I was expecting the directory to be generated when we run that. Are we supposed to make it beforehand? – Dawn17 Apr 24 '19 at 22:14
  • @Dawn17 also you should *not* to upvote the answer until you had enough help. Also I want to add that you should create these paths. may be manually may be via `os.mkdir` – sakost Apr 24 '19 at 22:15
  • I did not upvote it. So, we are expected to create those folders programmatically before creating the log files? – Dawn17 Apr 24 '19 at 22:15
  • I manually created the directories but I am still getting the same error. – Dawn17 Apr 24 '19 at 22:17
  • @Dawn17 may be you should to set the absolute path, because I bet you made the wrong directories due to not obvious CWD. Try to set the absolute path or to get the info about CWD via `print(os.getcwd())` and correct the paths due to that output – sakost Apr 24 '19 at 22:20
  • is the `cwd` the directory that I am calling the `open`? Does the path have to be based on `cwd`? – Dawn17 Apr 24 '19 at 22:22
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/192335/discussion-between-mr-morgan-and-dawn17). – sakost Apr 24 '19 at 22:22