2

So in python I'm trying to access a file path in the order of 000X

So I start by setting a string to

path = '0001' 

and then point to and open the file path

filepath = open('/home/pi/Pictures' + path + '.JPG', 'rb') 

so I do my business and now want to access the next file of extension 0002

intpath = int(path) intpath = intpath + 1 path = str(intpath) 

I'm sure this is inefficient, but I'm starting out. Unfortunately, this makes path '2' and not '0002'....any idea how I can maintain the leading zeros?

4 Answers 4

3

You can use something like this

>>> ['{0:04}'.format(i) for i in range(1, 15)] ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', '0014'] 
Sign up to request clarification or add additional context in comments.

Comments

2

If you know that you need 4 digits, use string formatting:

path = "%04d" % (intpath+1) 

Comments

0

I'd probably use one of the others, but for completeness, there's also zfill:

'1'.zfill(4) 

Comments

0

Another advantage of str.format is that it's easy to parameterise the width. If your Python is 2.5 or older you'll have to use the % formatting

>>> ['{i:0{width}}'.format(i=i, width=4) for i in range(1, 15)] ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', '0014'] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.