Built-in function

oct()

Converts a whole number to an octal (base 8) string that starts with 0o, such as 0o755. Use int(text, 8) to convert back.

BeginnerEvery example below runs in your browser. Change the code and press Run.

oct(x)

Octal is base 8: it uses only the digits 0 to 7. oct() turns a whole number into an octal string with the prefix 0o (zero and the letter o): oct(8) is '0o10'.

Today octal is mostly met in one place: file permissions on Linux and macOS, written like 755 or 644. Each digit there is a group of three yes/no bits for read, write and run.

In Python code you type an octal number with the same prefix: 0o755. A plain leading zero, as in 0755, is a SyntaxError in Python 3.

Parameters

ParameterWhat it is
x
required
A whole number (int).

Return value

A string starting with 0o (or -0o for negative numbers).

Examples

1Numbers in octal

Pythoneditable
for n in [7, 8, 9, 64, 493]:
    print(n, oct(n))
Output
7 0o7
8 0o10
9 0o11
64 0o100
493 0o755

2File permissions

0o644 is how you write the permission "owner can read and write, others can read" in Python.

Pythoneditable
mode = 0o644
print(mode)
print(oct(mode))
print(oct(mode)[-3:])
Output
420
0o644
644

3Read each permission digit

Pythoneditable
mode = 0o750
for who, digit in zip(["owner", "group", "others"], oct(mode)[-3:]):
    d = int(digit)
    rights = ("r" if d & 4 else "-") + ("w" if d & 2 else "-") + ("x" if d & 1 else "-")
    print(f"{who:<7}{digit} {rights}")
Output
owner  7 rwx
group  5 r-x
others 0 ---

4Back to a number, and without the prefix

Pythoneditable
print(int("755", 8))
print(int("0o755", 8))
print(format(493, "o"))
Output
493
493
755

Common mistakes

Writing octal with a plain leading zero

Older languages and Python 2 read 0755 as octal. In Python 3 it is a SyntaxError, so the program does not even start. Write 0o755.

Reading the letter o as a zero

In 0o10 the second character is the letter o, not a zero. 0o10 is 8, while 010 is an error and 10 is ten.

Pythoneditable
print(0o10)
print(10)
Output
8
10

Questions people ask

How do I convert octal to decimal in Python?

int("755", 8) gives 493.

How do I see a file's permissions in octal?

oct(os.stat("file.txt").st_mode)[-3:] gives the familiar three digits such as '644'.

Why does 0755 give a SyntaxError?

Python 3 removed the old leading-zero form because it was easy to misread. Use 0o755.

Spotted a mistake on this page? Tell us