-1

I cannot get using a variable in the filename to work without throwing an error.

def logData(name, info):
    currentTime = datetime.datetime.now()
    date = currentTime.strftime("%x")
    
    filename = "{}_{}.txt".format(name, date)

    f = open(filename, "a")
    f.write(info)+ '\n')
    f.close()

I have tried formatting the string as shown above as well as concatenating the variables.

Is there anything I can do to solve this?

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • Your parentheses definitely don't match up. Is the error you're getting "syntax error" perchance? – Silvio Mayolo Jul 07 '21 at 17:47
  • Does the file exist in the current working directory? If not, you need to provide the full path to `open(filename, 'a')`. If you're trying to *create* a file, you should open it in `write` mode and not `append` mode. – not_speshal Jul 07 '21 at 17:47
  • 1
    Make this a running program (fix syntax errors and include a line to call the function with a test name) and post the full traceback error message. We can run the same code and see what we get. – tdelaney Jul 07 '21 at 17:51
  • You're generating a filename with slashes in it - those are going to be interpreted as directory separators, referring to directories that almost certainly don't exist. – jasonharper Jul 07 '21 at 17:55
  • `print(filename)` will show you that the date string as slashes in it. Can you give us an example of what the filename should look like? The solution will be a different format string for `strftime`. – tdelaney Jul 07 '21 at 18:07

1 Answers1

1

One issue was the closing parentheses, also the date format contain / (slash ex:07/07/21) which will make the filename with slash i.e not a valid name in windows as it makes it a path.

Solution with least change to your logic:

import datetime

def logData(name, info):
    currentTime = datetime.datetime.now()
    date = currentTime.strftime("%Y-%m-%d")
    
    filename = "{}_{}.txt".format(name, date)
 
    with open(filename,"a+") as f:
        f.write(f'{info}\n')

logData('my_file',"test")
Abhi
  • 995
  • 1
  • 8
  • 12