0

Title is pretty self-explanatory. Currently I have:

with open('dwarf_fort.txt') as f:
    for minerals in f:
        mining_rig()

I need it to go from 'dwarf_fort.txt', execute the program and append the output into a new file. What am I missing here? Thank you.

  • Do you just want to write the output of the file to a different file? – M B Dec 17 '22 at 03:27
  • Yes please. I'm aware of using cmd for 'oldfile.txt > newfile.txt' but how can it be done within the script itself? – veryconfused Dec 17 '22 at 03:29
  • You open the second file as well as the `dwarf_fort` file, read from one and write to another. Check this answer: https://stackoverflow.com/a/50435835/3730626 – M B Dec 17 '22 at 03:33
  • @M B Hi thanks for the help. I have done this and when I open the output file it is blank. What's happened? – veryconfused Dec 17 '22 at 03:50
  • I have added an answer with working code. Compare the code from the answer below with your code and see what is missing. – M B Dec 17 '22 at 04:38

1 Answers1

1

This should work:

with open('dwarf_fort.txt') as f, open('out_f.txt', mode='w') as f1:
    for minerals in f:
        f1.write(minerals)

If the output file is still blank, do some checks:

  • Make sure the dwarf_fort.txt is in the same directory as the .py script.
  • Make sure the dwarf_fort.txt is not blank
  • Make sure your script is in a directory that is writeable to (so that the out_f.txt that gets created can be written to)
M B
  • 2,700
  • 2
  • 15
  • 20