python 基础 - 2.python 一些进阶操作

1

读取文件

1
2
3
4
5
6
7
8
9
file = open ("./pvuv.txt", 'r', encoding='utf-8')
for line in file.readlines ():
print (line)
file.close ()

file = open ("./pvuv.txt", encoding='utf-8')
for line in file:
print (line)
file.close ()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
with open ("./pvuv.txt", encoding='utf-8') as fin:
print (type (fin))
# 输出:<class '_io.TextIOWrapper'>

with open ("./pvuv.txt", encoding='utf-8') as fin:
print (fin)
# 输出:<_io.TextIOWrapper name='./pvuv.txt' mode='r' encoding='utf-8'>

with open ("./pvuv.txt") as fin:
print (fin)
# 输出:<_io.TextIOWrapper name='./pvuv.txt' mode='r' encoding='cp936'>

with open ("./pvuv.txt", encoding='utf-8') as fin:
for line in fin:
print (type (line))
# 输出:多行的 <class'str'>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
datas = []
with open ("./pvuv.txt") as fin:
is_first_line = True
for line in fin:
if is_first_line:
is_first_line = False
continue
datas.append (line [:-1].split ("\t"))
# 这里用 line [:-1] 是因为读取各行的时候会连换行符 '\n' 一起读取

# 也可以这样处理
datas = []
with open ("./pvuv.txt", encoding='utf-8') as fin:
for line in fin:
print (line [:].replace ('\n', ''))
1
2
3
4
5
txt = "Google#Runoob#Taobao#Facebook"
# 第二个参数为 1,返回两个参数列表
x = txt.split ("#", 1)
print x
# 输出:['Google', 'Runoob#Taobao#Facebook']