Doctapper
Doctapper

Reputation: 13

FileNotFoundError when creating a file using a variable in Python 3.5.1

I'm trying to create a file using a variable in Python, but it just won't have it. Here is the code that creates the filename:

a, b = time.strftime("%d/%m/%Y"), time.strftime("%H-%M-%S")
c = ("SCORE"+"-"+"("+a+")"+"-"+"("+b+")")
c = str(c+".txt")

This prints: SCORE-(28/12/2015)-(21-05-09).txt

That is the filename and file extension (.txt). So, I try to create a file using this, using this snippet of code:

file3 = open(c,"w+")
file3.write(file2a)
file3.close()

(file2a is the contents of a text file called SCORE.txt, this works properly).

When I execute this code, it gives me an error:

Traceback (most recent call last): File "E:\Program Files\Python guff\DocMarker\data\FinalScore.py", line 57, in file3 = open(c,"w+") FileNotFoundError: [Errno 2] No such file or directory: 'SCORE-(28/12/2015)-(21-05-09).txt'

This is baffling me, as when I changed the "c" bit to "test", it worked. Like this:

file3 = open("test", "w+")

This successfully created a file called "test" that had the contents of SCORE.txt inside of it. I'm baffled as to why it won't work with my "c" variable.

Upvotes: 1

Views: 1053

Answers (1)

Ben Glasser
Ben Glasser

Reputation: 3355

Because your filename has slashes in it, python is looking for a directory in

- SCORE-(28
  |
  - 12
    |
    - 2015)-(21-05-09).txt

try refactoring your initial code like this:

a, b = time.strftime("%d-%m-%Y"), time.strftime("%H-%M-%S")
c = ("SCORE"+"-"+"("+a+")"+"-"+"("+b+")")
c = str(c+".txt")

or, in a more compact and more readable way:

c = time.strftime("SCORE-(%d-%m-%Y)-(%H-%M-%S).txt")

Upvotes: 4

Related Questions