27

I'm trying to create a file with a unique file name for every time my script runs. I am only intending to do this to every week or month. so I chose to use the date for the file name.

f = open('%s.csv', 'wb') %name

is where I'm getting this error.

Traceback (most recent call last):
File "C:\Users\User\workspace\new3\stjohnsinvoices\BabblevoiceInvoiceswpath.py", line 143,      in <module>
f = open('%s.csv', 'ab') %name
TypeError: unsupported operand type(s) for %: 'file' and 'str'

it works if I use a static filename, is there an issue with the open function, that means you can't pass a string like this?

name is a string and has values such as :

31/1/2013BVI

Many thanks for any help.

vitaliis
  • 4,082
  • 5
  • 18
  • 40
jbaldwin
  • 924
  • 1
  • 7
  • 21

6 Answers6

49

You need to put % name straight after the string:

f = open('%s.csv' % name, 'wb')

The reason your code doesn't work is because you are trying to % a file, which isn't string formatting, and is also invalid.

Volatility
  • 31,232
  • 10
  • 80
  • 89
7

you can do something like

filename = "%s.csv" % name
f = open(filename , 'wb')

or f = open('%s.csv' % name, 'wb')

avasal
  • 14,350
  • 4
  • 31
  • 47
7

Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance

f = open('{}.csv'.format(name), 'wb')

Another option - the f-string formatting (ref):

f = open(f"{name}.csv", 'wb') 
ran632
  • 1,099
  • 1
  • 12
  • 14
5

And with the new string formatting method...

f = open('{0}.csv'.format(name), 'wb')
peixe
  • 1,272
  • 3
  • 14
  • 31
5

Even better are f-strings in python 3!

f = open(f'{name}.csv', 'wb')
Tom Lubenow
  • 1,109
  • 7
  • 15
-1
import hashlib

filename = file_for_download
with open(filename, "rb") as f:
    bytes = f.read()  # read entire file as bytes
    msg_hash = hashlib.sha256(bytes).hexdigest();
    print(f"MSG_HASH = {msg_hash}")
elby
  • 1
  • 3
    [A code-only answer is not high quality](//meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation. – Muhammad Mohsin Khan Mar 01 '22 at 14:13
  • 2
    This also does not answer the question. – wovano Mar 01 '22 at 16:45