0

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.

2
  • Well, does data/ exist? open won't create a folder. Commented May 12, 2016 at 18:54
  • /data does not exist Commented May 12, 2016 at 18:57

2 Answers 2

1

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):
    os.makedirs(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):
    os.makedirs(folder)

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

file_path = folder + filename + '.txt'

fout = open(file_path, 'w')
Sign up to request clarification or add additional context in comments.

Comments

0

Check if folder "data" does not exist. If does not exist you have to create it:

import os

file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt'
if not os.path.exists('data'):
    os.makedirs('data')
fout = open(file_name, 'w')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.