How to convert a string like '777' to an octal integer like 0777?

K

KB

Hi,

This may be a rudimentary question:

How to convert a string like '777' to an octal integer like 0777,
so that it can be used in os.chmod('myfile',0777)?

I know the leading zero is important in os.chmod.

KB
 
J

John Machin

KB said:
Hi,

This may be a rudimentary question:

How to convert a string like '777' to an octal integer like 0777,
so that it can be used in os.chmod('myfile',0777)?

I know the leading zero is important in os.chmod.

There is no law that says constant arguments to os.chmod have to be
expressed in octal -- it's just a historical accident that it's
convenient (for octal grokkers, anyway): there are 3 permissions (rwx)
and 2 ** 3 == 8.

Consider the following, whcih should provide enlightenment as well as
answer your question:

Cheers,
John
 
K

KB

Thanks, John.

But my point is how to keep the leading zero in 0777,
in order to be used in os.chmod('myfile', 0777)?
 
R

Robert Kern

KB said:
Thanks, John.

But my point is how to keep the leading zero in 0777,
in order to be used in os.chmod('myfile', 0777)?

I don't understand. The leading zero only exists in a particular string
representation. os.chmod() needs an integer, not a string. 0777 == 511.

os.chmod('myfile', 0777)
os.chmod('myfile', 511)
os.chmod('myfile', int('777', 8))

They all do *exactly* the same thing. End of story.

If you really need a string representation in octal (os.chmod()
doesn't), then use oct() on the integer.

--
Robert Kern
(e-mail address removed)

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
 
K

KB

The leading zero only exists in a particular string
representation. os.chmod() needs an integer, not a string. 0777 == 511.

Thanks, Robert.

What you said is exactly what I did not understand clearly,
because I am just a beginner in Python programming.

KB
 
S

Steven D'Aprano

Thanks, John.

But my point is how to keep the leading zero in 0777,
in order to be used in os.chmod('myfile', 0777)?

os.chmod('myfile', 0777)

Python will recognise integers written in octal if you leave a
leading zero, and in hex if you use a leading 0x or 0X.
24

As John pointed out, you don't have to use octal for chmod. You can use
decimal, or hex -- anything that is an integer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top