Python input/output¶

Printing and reading from the terminal¶

print¶

By default, the function print() will display all its arguments, separated by blanks, and will finally move to the next line.

In [1]:
print(1, 2, 3)
1 2 3

When adding a final name argument sep, one can temporarily redefine the separator which is used between each arguments to be displayed. For example, so move to the next line each time:

In [2]:
print(1, 2, 3, sep='\n')
1
2
3

One can also redefine end so to change the final print. For example, so to finally stay on the same line:

In [3]:
print(1, end='')
print(2, end='')
print(3, end='')
123

input¶

The function input() will display its single argument (the prompt and possible question), then collect anything you type until the next "return", and return the resulting string.

In [4]:
res = input("What's your name ? ")
print(res, type(res))
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[4], line 1
----> 1 res = input("What's your name ? ")
      2 print(res, type(res))

File ~/.cache/pypoetry/virtualenvs/pyplot-doc-VOfsvtlq-py3.11/lib/python3.11/site-packages/ipykernel/kernelbase.py:1186, in Kernel.raw_input(self, prompt)
   1184 if not self._allow_stdin:
   1185     msg = "raw_input was called, but this frontend does not support input requests."
-> 1186     raise StdinNotImplementedError(msg)
   1187 return self._input_request(
   1188     str(prompt),
   1189     self._parent_ident["shell"],
   1190     self.get_parent("shell"),
   1191     password=False,
   1192 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

If you expect an integer, you can go throw the int() function:

In [5]:
res = input("What's your age ? ")
print(res, type(res))
res = int(input("What's your age ? "))
print(res, type(res))
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[5], line 1
----> 1 res = input("What's your age ? ")
      2 print(res, type(res))
      3 res = int(input("What's your age ? "))

File ~/.cache/pypoetry/virtualenvs/pyplot-doc-VOfsvtlq-py3.11/lib/python3.11/site-packages/ipykernel/kernelbase.py:1186, in Kernel.raw_input(self, prompt)
   1184 if not self._allow_stdin:
   1185     msg = "raw_input was called, but this frontend does not support input requests."
-> 1186     raise StdinNotImplementedError(msg)
   1187 return self._input_request(
   1188     str(prompt),
   1189     self._parent_ident["shell"],
   1190     self.get_parent("shell"),
   1191     password=False,
   1192 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

Formatting any value into text¶

The method format() from the built-in type str provides multiples ways to transform whatever value into text.

Placehoders¶

The simpler way is to use a formatting string where all the "{}" are placeholders, where to insert values to be displayed.

In [7]:
x0, y0, z0 = 1, 2, 3
x1, y1, z1 = 4, 5, 6

my_format = "{}: x={}, y={}, z={}"

my_point0 = my_format.format("point0", x0, y0, z0)
print(my_point0)

my_point1 = my_format.format("point1", x1, y1, z1)
print(my_point1)
point0: x=1, y=2, z=3
point1: x=4, y=5, z=6

Numbered placehoders¶

One can use numbers between curly braces, for example to repeat certain values.

In [9]:
x0, y0, z0 = 1, 2, 3
x1, y1, z1 = 4, 5, 6

my_format = "{0}x={1}, {0}y={2}, {0}z={3}"

my_point0 = my_format.format("p0", x0, y0, z0)
print(my_point0)

my_point1 = my_format.format("p1", x1, y1, z1)
print(my_point1)
p0x=1, p0y=2, p0z=3
p1x=4, p1y=5, p1z=6

Formatting integers¶

When you know the value to be displayed will be an integer, you can add a colon : in the curly braces and a d just before the closing braces. Anything between : and d is additional formatting instructions.

In [11]:
print("{:04d}".format(10)) # At least 4 width, padded with 0
0010

Formatting floating point numbers¶

When you know the value to be displayed will be a floating point number, you can add a colon : in the curly braces and a f just before the closing braces. Anything between : and f is additional formatting instructions.

In [12]:
print("{:.10f}".format(0.1/3.)) # 10 digits after the dot
0.0333333333

Reading and writing a file¶

The current recommended way to open a file is the use of the with syntax, which ensure that the file will be closed in case of problem.

writing¶

The write() method require a string, and do not move to a new line, unless explicitly asked for with a \n:

In [13]:
with open("dummy.txt", 'w') as file:
    file.write("{}\n".format(1))
    file.write("{}\n".format(2))
    file.write("{}\n".format(3))
In [14]:
!cat dummy.txt
1
2
3

reading¶

When reading back the lines of a textual file, the line has kept the final \n, and you may want to remove it:

In [15]:
with open("dummy.txt", 'r') as file:
    for line in file:
        line = line.rstrip('\n')
        print(line)
1
2
3

Questions ?¶

See also:

  • PyFormat
  • The open() function