0

Cannot get my code to create a file. Initially I had hoped that I would be able to create a file where the name was "Stock Adjustment" and then the current date and time, however I cannot for the life of me find out what is wrong with my code. So then I changed it to be a simple text file named "Test.txt" however that still was not working.

The section of the code that is not working is as follows:

def reOrder():
with open("Test2.txt","a+") as stockFile:
    stockFile.write("Hi.")
    stockFile.close()
    print("done")

For clarifications sake it is worth noting that earlier in the program I did open a pre-existing file in read mode, however that was in a function that I hadn't called during testing, and I ensured to close the file once I was done. Also worth noting that I have tried changing a+ to w and w+ but to no avail.

1 Answers1

0

you don't write

with open("Test2.txt","a+") as stockFile:

instead you write:

stockFile = open ("Test2.txt","a+")

and you need to import os.

Try this:

import os
def reOrder():
     stockFile = os.open("Test2,txt","a+")
     stockFile.write("Hi")
     stockFile.close()
     print("done")
  • [Opening a file using the 'with' statement](https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for) is a good idea. In your code, there is no error handling. See also [The Open function explained](https://pythontips.com/2014/01/15/the-open-function-explained/). Also [os.open](https://docs.python.org/3/library/os.html#os.open) is intended for low-level I/O. The builtin function `open(...)` is appropriate here. – robert_x44 Jun 12 '17 at 02:46