This chapter will discuss some basic I/O functions.
Using print() to print strings to screen.
>>> print("Print")
PrintUsing .format(*args) with {} in the string to format the output:
>>> print("{0} and {1}.\n1: {1}, 0: {0}".format("First", "Second"))
First and Second.
1: Second, 0: FirstUsing input(prompt="") to get the input (string).
>>> x = input("enter a number for x? ")
enter a number for x? 10
>>> print(type(x))
<class 'str'>
>>> print(x)
10Using open(filename, mode="rt") to work with files.
! Always don't forget to close .close() the opened file.
There has some different modes:
| Mode | Description |
|---|---|
r |
Read (default). Only for file reading, error if file does not exist. |
a |
Append. Append text to the file, create file if file does not exist. |
w |
Write. Overwrite the file, create file if file does not exist. |
x |
Create. Create the file, error if file exists |
Also, you can specify the file type. Add it after the mode:
| Type | Description |
|---|---|
t |
Text (default) |
b |
Binary |
Add + for read and write the file:
file = open(filename, mode="r+") # from the beginning
file = open(filename, mode="w+") # from the beginning, overwrite.
file = open(filename, mode="a+") # from the end
file.close()Using read(length) to read file.
hello_world.txt:
Hello,
Python!
read file:
>>> file = open("hello_world.txt", "r")
>>> print(file.read())
Hello,
Python!
>>> print(file.read(3))
Hel
>>> file.close()Also, in another way:
file_content = ""
file = open("hello_world.txt", "r")
for line in file:
file_content += line
print(file_content)
# Hello,
# Python!
file.close()Using write() to write string to file.
According to the mode, it will append or overwrite.
file = open("hello_world.txt", "w")
file.write("Hello, world!") # overwrite
file.close()
file = open("hello_world.txt", "r")
print(file.read())
# Hello, world!