文件
先给出一个文件操作的方法
try:
with open("us.txt",'r') as infile:
for line in infile:
listVar = line.rstrip().split(‘,’);
print(listVar)
except IOError as exc:
print(exc)
read text
infile=open(“USPres.txt”,‘r’)
readlines() vs. readline() vs. read()
write text
创建程序与文件的连接(不存在,创建)
outfile = open(fileName,’w’)
###文本行写入
- 写入字符串列表
outfile.writelines(listVar) - 写入单个字符串
outfile.write(strVar) - 终止程序与文件的连接
outfile.close()
文本行追加
- 字符串列表
outfile.writelines(listVar) - 单个字符串
outfile.write(strVar) - 终止程序与文件的连接
outfile.close()
example
outfile = open("out1.txt",'a')
listVar = ['Today is Sunday\n', "Tommorow is Monday\n"]
outfile.writelines(listVar)
excute 3 times:
读写模式比较
对象序列化
- 定义:把对象从内存中变成可存储或可传输的过程
- 别名:Python中叫pickling,Java中叫serialization,其他语言中也被称为 marshalling,flattening等
- Python的pickle模块(序列化)
import pickle
example:
import pickle
##############################
# #
# 以二进制存储到文件 #
# 以二进制读取该文件 #
# 以二进制读取该文件 #
# 输出该文件 #
# #
#############################
lines = ['i like you',
'would you like me?',
'?????']
with open("lines.pkl",'wb') as outfile:
pickle.dump(lines,outfile)
outfile.close()
with open("lines.pkl",'rb') as infile:
lines_read = pickle.load(infile)
infile.close()
print(lines_read)
######################################################
# #
# then output: #
# ['i like you', 'would you like me?', '?????'] #
# #
######################################################
文件管理模块os
判断文件和目录
- 判断文件和目录
os.path.isabs() 是否为绝对路径
os.path.exists() 是否存在指定目录和文件
os.path.isdir() 是否为目录
os.path.isfile() 是否为文件
- 目录操作
os.getcwd() 获取当前工作目录
os.chdir() 改变工作目录
os.listdir() 列出目录下的文件
os.mkdir() 创建空目录
os.rmdir() 删除空目录
os.makedirs () 创建多级目录
os.removedirs() 递归删除多级目录
os.rmtree() 删除目录及下所有文件
- 文件操作
os.mknod() 创建空文件
os.remove() 删除文件
- 重命名文件和目录
os.rename() 重命名文件/目录
- 获取文件属性(路径,名称,后缀,大小)
os.path.dirname() 得到目录名
os.path.basename () 得到文件名
os.path.split() 分离目录名和文件名
os.path.splitext() 分离扩展名
os.path.getsize() 获取文件大小
- 复制和移动文件和目录
shutil.copyfile(‘old’, ’new’) 拷贝文件
shutil.copytree(‘old’,’new’) 拷贝目录(新目录不存在)
shutil.copy(‘old’,’new’) 拷贝文件到目录(存在)
shutil.move(‘old’,’new’) 移动文件到目录(存在)
Shutil 大量文件高级操作,特别是针对文件拷贝和删除的
CSV
- CSV(Comma-Separated Values)-
- 定义:每一行包含若干数据项,每一项之间使用逗号隔开。通常作为大型表格数据文件
- 访问格式:
# 创建程序与文件的连接
infile = open(fileName,’r’)
# 遍历文本行并使用split方法获得数据
for line in infile:
data = line.split(‘,’)
# 终止程序与文件的连接
infile.close()
example
infile = open(“USPres.csv”,’r’)
#遍历文件行
data=[]
for line in infile:
data += line.split(',')
#关闭文件
infile.close()
then output:
example
操作
解:
#Read file
infile = open("StuScore.csv",'r')
#Read column 1
listColumn1 =[ line.rstrip().split(',')[1] for line in infile ]
num = len(listColumn1)
#Mean
mean = sum( [ eval(score) for score in listColumn1 ] )/num
#Standard Deviation
standardDeviation = (sum([((eval(score)-mean)**2) for score in listColumn1])/num)**.5
#Median
listColumn1.sort()
m1 = int((num-1)/2)
m2 = int(num/2)
median = (eval(listColumn1[m1])+eval(listColumn1[m2]))/2
集合
两个集合上的操作(并、交、差等)
s <= t 或 s.issubset(t)
s >= t 或 s.issuperset(t)
s | t 或 s.union(t)
s & t 或 s.intersection(t)
s – t 或 s.difference(t)
s ^ t 或 s.symmetric_difference(t)
s |= t 或 s.update(t)
s &= t 或 s.intersection_update(t)
s -= t 或 s.difference_update(t)
s ^= t 或 s.symmetric_difference_update(t)
字典
定义:由“键:值”对组成的无序容器
表示:
{key1:value1, key2:value2,…}
特性:
键:无序、唯一、不可变对象(不能是list, set或dict)
值:不唯一,可以是任何数据类型
创建 (以stuAge = {‘Bob’: 19, ‘Darcy’: 18}为例)
空字典
d={ } ; d = dict()
静态创建
stuAge = {‘Bob’: 19, ‘Darcy’: 18}
从Iterable对象创建
stuAge = dict( [[‘Bob’,19], [‘Darcy’,18]] )
stuAge = dict( ((‘Bob’,19), (‘Darcy’,18)) )
从文本文件创建
infile = open(“stuAge.txt”,’r’)
stuAge = dict([ line.rstrip().split(‘,’) for line in infile])
infile.close()