输入输出
input()
- 接收一行字符串,遇 ‘\n’ 停止
输入只接受str
prompt= 'Please input: '
s = input(prompt)
print(s)
print()
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
"""
*objects:多个输出,代码以逗号分隔,输出以sep分隔
sep:输出以sep分隔,默认为空格
end:输出自带'\n',end=''不要回车
file:输出为流文件
flush:是否立即输出到流文件,不缓存,默认为False
"""
print([1,2], 'abc') # [1, 2] abc
print([1,2], 'abc', sep='***') # [1, 2]***abc
print([1,2], 'abc', end='') # 1, 2] abc 不输出回车
print([1,2] * 3) # [1, 2, 1, 2, 1, 2] *号表示重复3遍
文件
- 文件路径:/ (windows:/ 或 \\ 或 r’’)
- f:文件对象,输出可查看编码
- 任何文件的读取 都要处理异常 try-except
with open("files/text_file.txt") as f:
print(f)
# <_io.TextIOWrapper name='files/text_file.txt' mode='r' encoding='cp936'>
6种读写模式参数
以字符串读写
模式参数 | 描述 | 若文件不存在 | 若文件已存在 |
---|---|---|---|
r (模式参数省略,默认为’r’) | 读 | ||
w | 写 | 创建 | 覆盖 |
a | 写 | 创建 | 末尾追加,不覆盖 |
r+ | 读、写 | 覆盖 | |
w+ | 读、写 | 创建 | 覆盖 |
a+ | 读、写 | 创建 | 末尾追加,不覆盖 |
以二进制读写
基本6种模式参数+‘b’,如 rb、rb+
读文件(r、r+)
- 读文件(r、r+)一定要要异常处理(FileNotFoundError)
# 全部读取 f.read()
file_name = "files/text_file.txt"
try:
with open(file_name) as f:
content = f.read() # read():字符串
except FileNotFoundError:
print(f"{file_name} does not exist.")
# 逐行读取 f.readlines()
try:
with open(file_name) as f:
for line in f: # line:字符串
print(line)
except FileNotFoundError:
print(f"{file_name} does not exist.")
try:
with open(file_name) as f:
contents = f.readlines() # read():列表,每个元素为字符串(一行)
except FileNotFoundError:
print(f"{file_name} does not exist.")
写文件(w、w+、a、a+)
# 全部写 file_object.write()
content = "abc.def\n\t123\n\t345"
with open("text_file.txt", "w") as file_object:
file_object.write(content) # 字符串
# 逐行写
with open("text_file.txt", "w") as file_object:
file_object.write("abc.def\n")
file_object.write("\t123\n")
file_object.write("\t345")
# 追加写
with open("text_file.txt", "a") as file_object:
file_object.write("\n\t678")