Python Forum

Full Version: Writing to file in a specific folder
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Having trouble writing to a file in a specific directory. I'm using a loop to capture info from multiple devices so the actual filename is represented as a the variable "file"
 file = (hostname + '.txt')
 file = file.lstrip("\r\n")
 s = open('\\home\\verizon\\backups\\Cisco\\'%file ,'w')
 s.write(output)
 s.close()
s = open(f'/home/verizon/backups/Cisco/{file}' ,'w')
(Nov-13-2020, 05:03 PM)Axel_Erfurt Wrote: [ -> ]
s = open(f'/home/verizon/backups/Cisco/{file}' ,'w')

getting this error

Error:
[verizon@lab-gov-tac python]$ python iosbackup.py File "iosbackup.py", line 73 s = open(f'/home/verizon/backups/Cisco/{file}' , 'w') ^ SyntaxError: invalid syntax [verizon@lab-gov-tac python]$
Carrot belongs under the second quote (after {file})
F-strings (which this example uses) were introduced in python 3.6. You'll get a syntax error in earlier versions. What version are you using? Can you use a more recent copy?
For older version use

s = open("%s%s" % ('/home/verizon/backups/Cisco/', file), 'w')
Should use os.path or pathlib.