0

The script will generate multiple files using the year and id variable. These files need to be placed into a folder matching year and id. How do I write them to the correct folders?

file_root_name = row["file_root_name"]
year = row["year"]
id = row["id"]
path = year+'-'+id
try:
    os.makedirs(path)
except:
    pass
output = open(row['file_root_name']+'.smil', 'w')
output.write(prettify(doctype, root))
3
  • 1
    Are you asking how to put directory and file name together using os.path.join? Is that what you're struggling with? Commented Dec 30, 2011 at 23:11
  • The script will generate multiple files using the year and id variable. These files need to be placed into a folder matching year and id. Commented Dec 30, 2011 at 23:14
  • That's what the question says. Folder names and file names are combined with os.path.join. Are you asking how to use os.path.join? Commented Dec 30, 2011 at 23:15

1 Answer 1

2

If I understand your question correctly, you want to do this:

import os.path
file_name = row['file_root_name']+'.smil'
full_path = os.path.join(path, file_name)
output = open(full_path, 'w')

Please note that it's not very common in Python to use the + operator for string concatenation. Although not in your case, with large strings the method is not very fast. I'd prefer:

file_name = '%s.smil' % row['file_root_name']

and:

path = '%i-%i' % (year, id)
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for the clarification. I'm just beginning and learning by example.
with your methon I get TypeError: %d format: a number is required, not str
@DavidNeudorfer: Why is the year or id a string? They're usually numbers. If %i or %d don't work, you have a string, and must use %s.
@S.Lott: from a previous question I know that his year and id are coming from a csv.DictReader row, and are left as they're found, hence the strings.
@S.Lott I pulled year and id from a csv. id is the artist name and just happens to be the header for that column.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.