Solutions
Solutions

Reputation: 1

Making a new file in subdirectories using python

I am trying to create a file in a subdirectory, both of which will not exist when the program is first run. When I do this:

newfile = open('abc.txt','w')

It will create abc.txt just fine but the following will cause an error, saying the file or directory does not exist

newfile = open('folder/abc.txt','w')

I tried using os.makedirs to create the directory first but that failed as well raising the same error. What is the best way to create both the folder and file?

Thanks

Upvotes: 0

Views: 67

Answers (2)

ron rothman
ron rothman

Reputation: 18128

A couple of things to check:

  1. os.makedirs takes just the path, not the file. I assume you know this already, but you haven't shown your call to makedirs so I thought I'd mention it.

  2. Consider passing an absolute, not a relative, path to makedirs. Alternatively, use os.chdir first, to change to a directory in which you know you have write permission.

Hope those help!

Upvotes: 0

jgritty
jgritty

Reputation: 11915

>>> import os
>>> os.makedirs('folder')
>>> newfile = open('folder' + os.sep + 'abc.txt', 'w')
>>> newfile.close()
>>> os.listdir('folder')
['abc.txt']

This works for me

Upvotes: 1

Related Questions