开发者

String variables in python function?

I'm writing a 开发者_如何学Goscript 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??


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')


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜