Python 基础(四)
原文链接:http://www.one2know.cn/python4/
open函数
open(name[,mode[,buffering[,encoding]]])
mode(访问模式):
-1 : r(只读) w(只写,若文件存在则覆盖) a(追加) rb(二进制只读) wb(二进制只写)
-2 : ab(二进制追加) r+,w+,a+(都是读写) rb+,wb+,ab+(都是二进制读写)
r+,w+,a+区别
r+ :文件的指针调到文件头部
w+:如果文件不存在直接创建,存在覆盖源文件
a+ :文件的指针调到文件末尾- 打开关闭文件
open
#打开文件
file1 = open('python.txt','r')
print(file1)
#读写操作
#关闭文件
file1.close()
with open完成后自己自动关闭
with open('python.txt','r',encoding = 'utf-8') as file1:
content = file1.read()
print(content)
- 读文件
read(num):读取文件内容,num表示指定长度,如果没有则读取所有数据
file1 = open('python.txt','r',encoding = 'utf-8')
content = file1.read() #读取数据保存在content变量当中
print(content)
readlines()按行读取,返回一个列表,每一行的数据为一个元素,换行也会转换成str格式即'\n'
file1 = open('python.txt','r',encoding = 'utf-8')
content = file1.readlines() #逐行读取内容
print(content)
file1.close()
- 逐行读取
- 用
open结合for循环
file1 = open('python.txt','r',encoding = 'utf-8')
i = 1
for line in file1:
#没有使用read,像迭代器一样节省空间
print('这是第%d行:%s'%(i,line))
file1.close()
- 用
with结合for循环
with open('python.txt','r',encoding = 'utf-8') as file1:
i = 1
for line in file1:
#没有使用read,像迭代器一样节省空间
print('这是第%d行:%s'%(i,line))
i += 1
- 写入文件
write
#以写的方式打开一个文件
file1 = open('python.txt','w',encoding = 'utf-8') #覆盖源文件
#file1 = open('python.txt','a',encoding = 'utf-8') #追加
content = 'hello'
file1.write(content)
file.close()
with open('python.txt','w',encoding = 'utf-8') as file1:
#with open('python.txt','a',encoding = 'utf-8') as file1:
content = 'hello'
file1.write(content)
- 常用函数
flush把缓冲区内容写入硬盘
tell()查看文件指针
file1 = open('python.txt','r',encoding = 'utf-8')
str = file1.read(5) #读取数据保存在content变量当中
print('当前读取的数据是:'+str)
#查看当前指针位置
position = files.tell()
print('当前位置是:',position)
file1.close()
seek(offset[,whence])设置指针位置
offset是偏移量,whence有三个变量:0,1,2
0:从头开始算
1:从当前位置开始算
2:从末尾开始算
- 文件夹的操作,要
import os模块
import os
#获取当前路径
print(os.getcwd())
#列出当前(默认的)或指定目录的文件和文件夹
print(os.listdir('F:\python3.7\\))
#判断是否是一个文件
print(os.path.isfile('1.txt'))
#判断文件是否存在
print(os.path.exists('1.txt'))
#重命名文件
os.rename('1.txt','2.txt')
#删除文件
os.remove('2.txt')
#将目录和文件分割成2个元素,作为列表输出
os.path.split(F:\python3.7\1.txt)
#创建目录
os.mkdir('py')
#删除目录
os.rmdir('py')
- 异常处理
try except else finally - 简单异常处理
try:
print(a) #如果有错,就会捕获到异常
except ValueError:
print('变量未定义') #ValueError对异常的处理
except NameError:
print('变量未定义') #NameError对异常的处理
#捕获异常的具体信息
try:
print(a)
file = open('a.txt','r')
except (NameError,FileNotFoundError) as e: #异常元组,若不知道什么异常可以用基类Exception
print(e) #打印异常的具体信息,捕捉第一个异常就输出了
else没有异常时执行的语句finally不管有没有异常都执行- 常用模块—
time模块
import time
print(time.altzone) #返回格林威治西部的夏令时地区的偏移秒数
print(time.asctime()) #默认返回可读形式的当前时间
print(time.asctime((2017,12,12,12,12,12,3,340,1))) #返回可读形式的时间,感觉没啥用啊
print(time.gmtime()) #返回时间元组,格林威治时间的元组
print(time.localtime()) #返回本地时间元组
print(time.clock()) #返回进程时间,以秒为单位记时间戳
print(time.ctime()) #获取当前时间
print(time.time()) #返回当前时间的时间戳,从今年1月1日0点到现在的秒数
for i in range(3):
print(1)
time.sleep(2) #睡眠两秒
格式化时间:时间戳->时间元组->时间字符串
import time
times = time.time() #获取当前时间戳
formatTime = time.localtime(times)
print(time.strftime('%Y-%m-%d %H:%M:%S'.formatTime))
#time.strptime将时间字符串转换为时间元组
times = '2017-12-12 12:12:12'
formatTime = time.strptime(times,'%Y-%m-%d %H:%M:%S')
print(formatTime)
#mktime将时间元组转换为时间戳
print(time.mktime(formatTime))
- 三天前的时间
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()-3*24*60*60))) - 进程与线程
import time
import threading
#单线程
def music(name,loop):
for i in range(loop):
print('listen music %s %s'%(name,time.ctime()))
time.sleep(1)
def movie(name,loop):
for i in range(loop):
print('watch movie %s %s'%(name,time.ctime()))
time.sleep(1)
if __name__ = '__main__':
music('music1',3)
movie('movie2',2)
print('end time %s'%time.ctime())
#创建多线程:假多线程,不建议使用
t1 = threading.Thread(target = music,args = ('music1',3))
t2 = threading.Thread(target = movie,args = ('movie2',2))
if __name__ = '__main__':
#守护主线程,主线程结束杀死子线程
t1.setDaemon(True)
t2.setDaemon(True)
#启动线程
t1.start()
t2.start()
#对主线程进行阻塞,等所有的子线程运行结束,再运行主线程
t1.join()
t2.join()
print('end time %s'%time.ctime())
- 全局解释锁GIL
#加锁
balance = 0
def change(n):
global balance
balance += n
balance -= n
lock = threading.Lock() #获取线程锁
def run_thread(n):
for i in range(100000):
#获取锁
lock.acquire()
try:
change(n)
finally:
#释放锁
lock.release()
t1 = threading.Thread(target = run_thread,args = (4,))
t2 = threading.Thread(target = run_thread,args = (8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)
- 多进程:用
multiprocessing代替Thread
单进程
import time
def work1(f,n):
print('work1 start')
for i in range(n):
with open(f,'a') as fs:
fs.write('hello\n')
time.sleep(1)
print('work1 end')
def work2(f,n):
print('work2 start')
for i in range(n):
with open(f,'a') as fs:
fs.write('world\n')
time.sleep(1)
print('work2 end')
if __name__ = '__main__':
work1('1.txt',3)
work2('1.txt',3)
多进程加锁
import time
import multiprocessing
def work1(f,n,lock):
print('work1 start')
lock.acquire()
for i in range(n):
with open(f,'a') as fs:
fs.write('hello\n')
time.sleep(1)
print('work1 end')
lock.release()
def work2(f,n,lock):
print('work2 start')
lock.acquire()
for i in range(n):
with open(f,'a') as fs:
fs.write('world\n')
time.sleep(1)
print('work2 end')
lock.release()
if __name__ = '__main__':
lock = multiprocessing.Lock()
p1 = multiprocessing.Process(target=work1,args=('1.txt',3,lock))
p2 = multiprocessing.Process(target=work2,args=('1.txt',3,lock))
p1.start()
p1.start()
- 进程池
pool
import os
import multiprocessing
import time
def work(n):
print('run work(%s),work id %s'%(n,os.getpid()))
time.sleep(5)
print('work(%s) stop,work id %s'%(n,os.getpid()))
if __name__ = '__main__':
print('parent process %s.'% os.getpid())
#创建进程池
p = multiprocessing.Pool(3)
for i in range(5):
#创建5个进程
p.apply_async(work,args=(i,))
p.close()
p.join()
pandas数据分析包
引入约定:
drom pandas import Series,DataFrame系列,帧
import pandas as pd
Series:类似一维数组的对象,索引值是可以重复的
DataFrame:表格型,没列可以是不同的数据类型,既有行索引也有列索引- 通过一维数组创建
Series
import pandas as pd
#通过一维数组创建Series
ser01 = pd.Series([1,2,3,4])
ser01
print(ser01.dtype) #获取类型,输出: int32
print(ser01.values) #获取值,输出: [1 2 3 4]
print(ser01.index) #获取索引,输出: RangeIndex(start=0,stop=4,step=1)
#设置索引 通过 index 属性
ser01.index = ['a','b','c','d']
ser01
#也可以在创建时设置属性
ser02 = pd.Series(np.Series(np.array([1,2,3,4]),dtype = np.float64,index = ['a','b','c','d'])
#通过字典的方式创建
ser02 = pd.Series({'a':10,'b':20,'c':30})
ser02
#获取Series
print(ser02['a']) #通过key,输出:10
print(ser02[0]) #通过坐标,输出:10
print(ser02[0:2]) #类似切片,含左不含右,输出2对数据
print(ser02['a':'c']) #类似切片,但输出3对数据
Numpy的运算Series基本都可以用
import pandas as pd
ser01 = pd.Series([1,2,3,4])
ser01+1 #每个数都+1,很简单
Series缺失值处理
ser01 = pd.Series([1,2,3])
ser02 = pd.Series(ser01,index=['a','b','c','d'])
ser02 #缺失的数据用NaN来代替
ser02[pd.isnull(ser02)]
ser02[pd.notnull(ser02)] #过滤掉缺失值
Series自动对齐:有的自动对齐,没有的自动NaN
ser01 = pd.Series([1,2,3,4],index = ['a','b','c','d'])
ser02 = pd.Series([10,20,30,40],index = ['e','a','b','f'])
print(ser01+ser02)
'''
输出:
a 21.0
b 32.0
c NaN
d NaN
e NaN
f NaN
'''
Series的name属性
ser01.name总名字
ser01.index.name第一列索引名DataFrame创建
df01 = pd.DataFrame(['joe','susan','anne'],[70,80,90],index = ['one','two','three'],columns = ['name','score'])
通过字典方式创建
df01 = pd.DataFrame({
'name':['joe','susan','anne'], #key 变成列索引
'age':[18,19,20],
'class':3
},index = ['one','two','three'])
print(df01) #输出一个表
DataFrame数据处理
df01['name']通过列索引获取数据
df01['address'] = ['shanghai','beijing','hangzhou']添加列数据
df01.pop('address')列删除
df01.ix['one']行获取,古老的方法
df01.loc['two']行获取
df01.ix['four'] = ['batman',25,4]行修改,没这行就添加,有这行就修改
df02 = df01.drop('four')行删除pandas基本操作
import pandas as pd
#读取文件
df01 = pd.read_csv('data1.csv') #读取csv
print(df01)
df02 = pd.read_excel('data1.xlsx') #读取excel
print(df02)
df03 = pd.read_csv('data1.txt',sep = ';',header = None)
#读取txt,sep表示用什么分割,header=None表示不用第一排作为列索引
print(df03)
Python 基础(四)的更多相关文章
- Python 基础 四 面向对象杂谈
Python 基础 四 面向对象杂谈 一.isinstance(obj,cls) 与issubcalss(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls ...
- Python基础(四) 基础拾遗、数据类型进阶
一.基础拾遗 (一).变量作用域 外层变量,可以被内层变量直接调用:内层变量,无法被外层变量使用.这种说法在其它语言中适用,在python中除了栈以外,正常的变量作用域,只要执行声明并在内存中存在,该 ...
- 【笔记】Python基础四:迭代器和生成器
一,迭代器协议和for循环工作机制 (一),迭代器协议 1,迭代器协议:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个stopiteration异常,以终止迭代(只能往 ...
- python 基础(四) 函数
函数 一.什么是函数? 函数是可以实现一些特定功能的 小方法 或者是小程序 优点: 提高 了代码的后期维护 增加了代码的重复使用率 减少了代码量 提高了代码可读性 二.函数的定义 使用 def关键+函 ...
- python基础四(json\os\sys\random\string模块、文件、函数)
一.文件的修改 文件修改的两种思路: 1.把文件内容拿出来,做修改后,清空原来文件的内容,然后把修改过的文件内容重新写进去. 步骤: 1.打开文件:f=open('file','a+') #必须用a ...
- Python基础四
1. 集合 主要作用: 去重 关系测试, 交集\差集\并集\反向(对称)差集 2. 元组 只读列表,只有count, index 2 个方法 作用:如果一些数据不想被人修改, 可以存成元组,比如身 ...
- python基础(四)运算
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python的运算符和其他语言类似 (我们暂时只了解这些运算符的基本用法,方便我们 ...
- python基础四-文件读取
文件读取 open()接受一个参数:要打开的文件名, 并返回一个表示文件的对象, 存储到后面的变量中 python会在当前执行文件所在目录查找 可以使用绝对路径, 在linux中使用'/', 在win ...
- Python基础(四) socket简单通讯
socket:我们通常听过的套接字: 服务端: 1.创建socket对象 2.bing 绑定ip及端口 3.对该端口进行监听 4.消息阻塞(等待客户端消息) 客户端: 1.创建socket对象 2.连 ...
- python基础(四)字符串处理
字符串处理 msg = 'my name is sylar' capitalize方法,将字符串的首字母大写 print 'capitalize方法:', msg.capitalize() swapc ...
随机推荐
- python输出九九乘法表
1.脚本如下 (1)倒三角格式的,注意行前的空格 for i in range(1,10): for j in range(i,10): print("%d*%d= ...
- spring autowrited注解
@Autowired 注释,它可以对类成员变量.方法及构造函数进行标注,完成自动装配的工作. 通过 @Autowired的使用来消除 set ,get方法.在使用@Autowired之前,我们对一个b ...
- 虚IP解决程序连只读服务器故障漂移
目前公司有一套核心交易数据库配置了AlWaysON,SQL 2012版本, 1主4从, 其从库(8,14, 8.15) 这2台只读的从数据库服务器, 后台程序和wms等很多程序,都是直接配置IP连接这 ...
- 【Android】Field requires API level 4 (current min is 1): android.os.Build.VERSION#SDK_INT
刚遇到了这个问题: Field requires API level 4 (current min is 1): android.os.Build.VERSION#SDK_INT 解决方法: 修改 A ...
- spring boot 学习笔记(一)之前端文件配置
一.叙述 spring boot 由于是内置的tomcat ,因此其在独立运行的时候,是不需要单独安装 tomcat,这使其前端文件(CSS.JS.html)等放置的位置与war中的不同. 二.常见配 ...
- mysql 学习第一天
RDBMS 术语 在我们开始学习MySQL 数据库前,让我们先了解下RDBMS的一些术语: 数据库: 数据库是一些关联表的集合. 数据表: 表是数据的矩阵.在一个数据库中的表看起来像一个简单的电子表格 ...
- 深入理解Apache Kafka
一.介绍 Kafka在世界享有盛名,大部分互联网公司都在使用它,那么它到底是什么呢? Kafka由LinkedIn公司于2011年推出,自那时起功能逐步迭代,目前演变成一个完整的平台级产品,它允许您冗 ...
- 数据结构之稀疏矩阵C++版
//只是简单的演示一下,这个实际运用视乎不怎么多,所以java版不再实现 /* 希疏矩阵应用于对数据的压缩,仅仅保留不为0的数据 稀疏矩阵的转置,可以由多种方式,下面演示的稍显简单,时间复杂度略高O( ...
- 关于 java中的换行符
java中实现换行有以下3种方法: 1.使用java中的转义符"\r\n": String str="aaa"; str+="\r\n"; ...
- C++基础之:扫雷破解
版权声明: 本文原创发布于博客园"优梦创客"的博客空间(网址:http://www.cnblogs.com/raymondking123/)以及微信公众号"优梦创客&qu ...