Search code examples
pythontext-filesfilenames

How to solve the error in writing to a text file


When I run the following code, instead of creating a text file in my working directory with the name '03/08/2020.txt', it generates an error FileNotFoundError: [Errno 2] No such file or directory: '03/08/2020.txt'. As far as I think, it is just because of the slashes. But anyhow, I want to create a text file with slashes because this thing is a part of a large code and I have to work with dates (for attendance purposes).

dates = ['03/08/2020', '1', '2', '3']
def test(alist):
    myfile = open(alist[0])+'.txt', 'w')
    for i in alist:
        myfile.write(f"{i}\n")
myfile.close()
test(dates)

is there a way yo handle this issue?


Solution

  • As jdaz said, you can instead use "03-08-2020.txt"

    This is because on windows, you can't add to the following characters to your file names:

    \ / : * ?  " < > |
    

    If you try to rename a file with one of those characters, you'll see a message saying you can't do so.