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?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Zac1
  • 208
  • 7
  • 34

1 Answers1

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Also probably prefer `snake_case` for your variables instead of `dromedaryCase` – tripleee Nov 11 '20 at 07:07
  • 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! – Zac1 Nov 11 '20 at 16:32
  • Simply copy/paste into an editor. Or try https://ideone.com/wTuKIB – tripleee Nov 11 '20 at 16:45
  • 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! – Zac1 Nov 11 '20 at 17:02