Jack Frye Jack Frye - 1 year ago 67
Python Question

Creating Directories Python

My instructor provided the following code, but it is not working on OS X when run from command line.

file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt'
fout = open(file_name, 'w')

Error message:

Traceback (most recent call last):
File "write_a_poem_to_file.py", line 12, in <module>
fout = open(file_name, 'w')
IOError: [Errno 2] No such file or directory: 'data/poem1.txt'

I have been writing Python since before I got to the class and having done a little research, it think you need to import the os module to create a directory.

Then you can specify that you want to create a file in that directory.

I believe you might also have to switch into that directory before accessing files.

I may be wrong, and I am wondering if I am missing another issue.

Answer Source

As stated by @Morgan Thrapp in the comments, the open() method won't create a folder for you.

If the folder /data/ already exists, it should work fine.

Otherwise you'll have to check if the folder exists, if not, then create the folder.

import os 

if not os.path.exists(directory):

So.. your code:

file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt'
fout = open(file_name, 'w')

Became something like this:

import os

folder = 'data/'

if not os.path.exists(folder):

filename = raw_input('Enter the name of your file: ')

file_path = folder + filename + '.txt'

fout = open(file_path, 'w')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download