Abhilash Muthuraj
Abhilash Muthuraj

Reputation: 2028

String variables in python function?

I'm writing a script in python, but not able to use multiple stings in cases like check directory, file creation etc,

I'm using this to get user input : drive = raw_input('enter drive name to make backup ')

if not os.path.exists('/media/%s/backup' %drive):
    os.mkdir('/media/%s/backup' %drive)

The above code is working, but the tarfile below is giving an error........

./backup4.py 
enter drive name to make backup PENDRIVE
Traceback (most recent call last):
  File "./backup4.py", line 17, in <module>
    tarFile = tarfile.open("/media/%s/backup/%s.tar.bz2" %drive %dateVar, 'w:bz2')
TypeError: not enough arguments for format string


tarFile = tarfile.open("/media/%s/backup/%s.tar.bz2" %drive %dateVar, 'w:bz2')

what changes should i make to above tarfile.open??

Upvotes: 0

Views: 228

Answers (2)

Chaos Manor
Chaos Manor

Reputation: 1220

I would suggest to keep the formatting stuff out of the tarfile.open() as in the following snippet of code:

file_name = "/media/{0}/backup/{1}.tar.bz2".format(drive, dateVar)
tarFile = tarfile.open(file_name, 'w:bz2')

In this way you can reuse your file_name with the proper formatting in other portions of your script.

Upvotes: 2

Sam Dolan
Sam Dolan

Reputation: 32532

Your string formatting is incorrect. You need to pass a tuple of variables equal to the amount of substitutions in your string.

tarFile = tarfile.open("/media/%s/backup/%s.tar.bz2" % (drive, dateVar), 'w:bz2')

Upvotes: 6

Related Questions