目录
1.标准输入输出流
import sys
a = input("input a: ")
b = sys.stdin.readline()
c = sys.stdin.readline().strip()
d = sys.stdin.readline().strip()
e = sys.stdin.readlines()
print(a, type(a))
print(b, type(b))
print(c, type(c))
print(d, type(d))
print(e, type(e))
for line in sys.stdin:
print(line)
a = line.split()
print(int(a[0]) + int(a[1]))
for s in sys.stdin:
s = s.strip()
for x in s:
if x.isupper():
s = s + x
s = s[0:s.index(x)] + s[s.index(x) + 1:]
print(s)
if __name__ == "__main__":
# 读取第一行的n
a = input()
b = input()
c = list(map(int, a.split()))
d = list(map(int, b.split()))
print(type(a))
print(a[0])
print(b)
print(type(c))
print(c[0])
print(d)
for line in sys.stdin.readlines():
if not line:
break
else:
print(line)
# 输出一维列表
a = int(input())
s = []
for i in range(a):
b = input()
print(type(b))
print(b)
c = b.split()
print(type(c))
print(c)
# s = s + c
# s.append(c)
s.extend(c)
print(s)
print(s[0])
print(s[1][2])
# 输出二维列表
a = int(input())
s = []
for i in range(a):
b = input()
c = list(map(int, b.split()))
s = s + [c]
print(s)
n = int(sys.stdin.readline().strip())
point = []
for i in range(n):
point.append(list(map(int, sys.stdin.readline().strip().split())))
print(point)
# #让输出加空格
a = int(input())
s = str()
for i in range(a):
b = input()
s = s + ' ' + b.strip()
print(s)
# 内部定义字符串
if __name__ == "__main__":
# 读取第一行的n
a = str('abc')
print(type(a))
print(a)
2.目录操作
import os
print(os.name) # nt, 操作系统类型
# 查看当前目录的绝对路径:
print(os.path.abspath('.')) # G:\code\python\basic
# 在某个目录下创建一个新目录,首先把新目录的完整路径表示出来:
# os.path.join('/Users/michael', 'testdir') # '/Users/michael/testdir'
# # 然后创建一个目录:
# os.mkdir('/Users/michael/testdir')
# # 删掉一个目录:
# os.rmdir('/Users/michael/testdir')
print(os.path.split('/Users/michael/testdir/file.txt'))
print(os.path.splitext('/path/to/file.txt'))
# 这些合并、拆分路径的函数并不要求目录和文件要真实存在,它们只对字符串进行操作。
3.文件读写
f = open('/Users/michael/test.txt', 'r')
f.read()
f.close()
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
with open('/path/to/file', 'r') as f:
print(f.read())
for line in f.readlines():
print(line.strip()) # 把末尾的'\n'删掉
f = open('/Users/michael/test.jpg', 'rb')
f.read()
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
f.read()
f = open('/Users/michael/test.txt', 'w')
f.write('Hello, world!')
f.close()
with open('/Users/michael/test.txt', 'w') as f:
f.write('Hello, world!')