0

I have a bunch of Python arrays such as;

fileNameArray = ['fileName1', 'fileName2', 'fileName3']
titleArray = ['aTitle', 'bTitle', 'cTitle']
tagArray = ['abc', 'def', 'ghi', 'jkl', 'mno']

So, when I run the program, the output should be three files with names 'fileName1.mdx', 'fileName2.mdx', 'fileName3.mdx' with its content looking like;

---
title: 'aTitle'
Date Added: '2020-11-11'
summary: 'xyz.'
image: '/static/images/123.png'
tags: 'abc, def, ghi, jkl, mno'
---

When I run the program, how do I create a file named fileNamex.mdx with names coming from the fileNameArray, and its contents like title tag coming from the titleArray and tag key values coming from the tagArray.

Other keys like summary and image are static, that is the same values shown in the example should be on all files.

So, basically, how do I create files in Python (On Windows) and populate them with the initial content shown above?

0

1 Answer 1

0

Something like this?

for file, title in zip(fileNameArray, titleArray):
    with open(file + '.mdx', 'w') as handle:
        for line in (
                "---", "title: '" + title + "'",
                "summary: 'xyz'", "image: ''/static/images/123.png'",
                "tags: '" + ", ".join(tagArray) + "'", "---"):
            handle.write(line + '\n')

Stylistically f"title: '{title}'" would arguably be more elegant, but then an f-string would be rather unreadable and bewildering for the "tags: ..." case, so I went with simple string concatenation throughout. A third option is to use the legacy string formatting "title: '%s'" % (title) etc.

Sign up to request clarification or add additional context in comments.

4 Comments

Also probably prefer snake_case for your variables instead of dromedaryCase
Hi, as you can tell from the question, I am new to this. Is there a way you can give me the whole program which I can test? Or did you not test it yet? Thanks!
Simply copy/paste into an editor. Or try ideone.com/wTuKIB
It worked, but I was basically looking for how to initialize the arrays, but just copy-pasting my array code worked. Then I ran it locally because ideone can't let you create files? But thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.