1

I'm new to Python and i'd like to build a script (Python 3) to test electronic modules and save log files. I'd like to save the logfiles in the following format:

201410log.txt (yearmonthlog.txt)

This is done with the code:

import os

logfile=open(time.strftime('%Y%mlog.txt'), 'a') 
logfile.write('This is a test\n\n\n')               

This way, every month a new log file is created. However, i'd like the logfiles to be in in a subdirectory (\logs).

I tried approaches like

logfile=open(time.strftime('\logs\%Y%mlog.txt'), 'a')   

and similar things but i couldnt get any of them to work. I searched trough other questions on stackoverflow (for example: Relative paths in Python ) and elsewhere in the internet, but i couldnt find the right solution. Could someone point me in the right direction?

(sorry for any mistakes/spelling errors, i'm no native english speaker)

Community
  • 1
  • 1
lenny
  • 17
  • 7

1 Answers1

1

Remove the leading backslash. It makes the path absolute. Beside that, you need to escape a backslash.

logfile = open(time.strftime('logs\\%Y%mlog.txt'), 'a')   

or use r'raw string literal':

logfile = open(time.strftime(r'logs\%Y%mlog.txt'), 'a')   

For your current path string literal, it does not make problem. But paths like 'a\nb' will not work because \n is interpreted as newline instead of a literal backslash and n.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • thank you! this already solved my question. would it make any sense if i use `logfile = open(time.strftime(**r**'logs\\%Y%mlog.txt'), 'a')` – lenny Oct 16 '14 at 14:59