python学习之基础篇(文件、集合与字典)6

文件

先给出一个文件操作的方法

在这里插入图片描述

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()

  • readline() 只读一行,返回单个str
  • readlines() 每行作为一个元素,返回str列表
  • read() 读所有行,返回单个str
  • example

在这里插入图片描述

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

判断文件和目录

  1. 判断文件和目录
os.path.isabs()				是否为绝对路径
os.path.exists()			是否存在指定目录和文件
os.path.isdir()				是否为目录
os.path.isfile()			是否为文件
  1. 目录操作
os.getcwd()					获取当前工作目录
os.chdir()					改变工作目录
os.listdir()				列出目录下的文件
os.mkdir()					创建空目录
os.rmdir()					删除空目录
os.makedirs ()				创建多级目录
os.removedirs()				递归删除多级目录
os.rmtree()					删除目录及下所有文件
  1. 文件操作
os.mknod() 					创建空文件		
os.remove()					删除文件	
  1. 重命名文件和目录
os.rename()					重命名文件/目录
  1. 获取文件属性(路径,名称,后缀,大小)
os.path.dirname()			得到目录名
os.path.basename ()			得到文件名		
os.path.split()				分离目录名和文件名
os.path.splitext()			分离扩展名
os.path.getsize()			获取文件大小		
  1. 复制和移动文件和目录
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

操作

  • 文件导入列表
    listOfRecords = [line.rstrip() for line in infile]
    

    要求:

在这里插入图片描述

解:

#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()

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值