0

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?

Subbu VidyaSekar
  • 2,503
  • 3
  • 21
  • 39
Adnan Akram
  • 186
  • 2
  • 12
  • 2
    Fix the fourth line, it should be `myfile = open(alist[0] + '.txt', 'w')`. You put an unnecessary parenthesis there – NMrocks Aug 04 '20 at 03:44
  • 3
    You are going to run into a bunch of issues either now or later if you try to use slashes in your file names. Use hyphens instead. `03-08-2020.txt` – jdaz Aug 04 '20 at 03:46
  • 1
    The last line of the function is incorrectly indented. – DYZ Aug 04 '20 at 03:47

1 Answers1

1

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.

tim
  • 52
  • 5