Python基础练习
近日,因工作需要要学习Python。为了不在语言细节中无法自拔,我按照网上广为流传的《程序员技术练级攻略》中python部分的学习计划,做了三个简单的练习,算是对python有了初步的了解。
1.使用open/csv进行文件读写操作。
__author__ = 'xuqiang'
# -*- coding: UTF-8 -*-
import csv
import sys #csv操作,文件格式不是重要的,最重要的是文件内容要符合格式,而不是文件扩展名 #利用open进行逐行处理
print("逐行处理\n")
for line in open("Sample.txt"): #取一行
title,year,director = line.split(",")
print(year,title) for line in open("Sample.txt"): #取一行
title,year,director = line.split(",")
print(title,director) #使用CSV进行逐行处理CSV格式的文件
print("\ncsv处理")
reader = csv.reader(open("Sample.txt"))
for title,year,director in reader:
print title,director #使用CSV进行逐行处理修改了分隔府的CSV格式的文件
print"\n改变分隔符"
class SKV(csv.excel):
delimiter = ";"
csv.register_dialect("SKV", SKV)
reader = csv.reader(open("Sample.ddd"),"SKV")
for title,year,director in reader:
print year,title print("\n 改变分隔符简单版本")
reader = csv.reader(open("Sample.ddd"),delimiter=";")
for title,year,director in reader:
print year,title #使用CSV将数据写入到CSV格式的文件中
print("\n 将数据读取出来然后存储到CSV格式的文件中")
reader = csv.reader(open("Sample.ddd"),delimiter=";")
data = []
for title,year,director in reader:
tup = (title,year,director) #先存到元组
data.append(tup) #再将元组存储到列表 newfile = open('outCsv.csv','w') #一个新文件
sys.stdout = newfile #sys.stdout原本是控制台,我们重定向到newfile上
writer = csv.writer(sys.stdout) for item in data: #列表的迭代
writer.writerow(item) #一行一行的写入
2.文件系统的遍历 ,并将遍历结果进行排序
__author__ = 'xuqiang'
# -*- coding: UTF-8 -*- import os
import os.path
import time
import operator rootdir = "/home/xuqiang/newfiles" #一、使用os.walk进行文件夹遍历,直接输出遍历结果 #os.walk会递归遍历整个文件夹 该方法对于每个目录返回一个三元组,(dirpath, dirnames, filenames)
#parent:dirnames 一般就一个,当前的大文件夹名称
#dirnames: 此文件夹中所有的文件夹名称
#filenames: 此文件夹中所有的文件名称
for parent,dirnames,filenames in os.walk(rootdir):
for dirname in dirnames:
print "parent is :" + parent
print "dirname is :" + dirname + '\n' for filename in filenames:
print "parent is :" + parent
print "filename is:"+ filename
print "the full name of the file is:" + os.path.join(parent,filename) + '\n' #输出文件路径信息 #二、使用os.path.walk进行文件夹遍历,将遍历结果写入文件中 #将文件属性中的时间改为‘2011-1-12 00:00:00格式'
def formattime(localtime):
endtime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(localtime))
return endtime #searchdir是os.path.walk的回调函数,os.path.walk也会递归遍历文件夹
#dirname:路径
#names:文件列表(只有文件名)
def searchdir(arg,dirname,names):
for filespath in names:
fullpath=os.path.join(dirname,filespath) #路径名+文件名 = 文件绝对路径
statinfo=os.stat(fullpath) #文件属性
sizefile=statinfo.st_size #文件大小
creattime=formattime(statinfo.st_ctime) #创建时间
maketime=formattime(statinfo.st_mtime) #修改时间
readtime=formattime(statinfo.st_atime) #浏览时间
if os.path.isdir(fullpath): #判断是文件夹还是文件
filestat='DIR'
else:
filestat='FILE'
#把结果写入到test.txt中
open ('test.txt','a').write('【%s】路径:%s 文件大小(B):%s 创建时间:%s 修改时间:%s 浏览时间:%s\r\n'%(filestat,fullpath,sizefile,creattime,maketime,readtime)) os.path.walk(rootdir,searchdir,()) #三、利用os.list进行文件夹遍历,并对遍历结果按照不同要求进行排序
tuplist = []
for i in os.listdir(rootdir):
fullpath = os.path.join(rootdir,i)
statinfo=os.stat(fullpath) #文件属性
sizefile=statinfo.st_size #文件大小
creattime=formattime(statinfo.st_ctime) #创建时间
if os.path.isfile(fullpath):
tup = {'filename':i,'filesize':sizefile,'filetime':creattime}
tuplist.append(tup) tuplist.sort(key=operator.itemgetter('filetime') ) #根据创建时间进行排序
print tuplist
tuplist.sort(key=operator.itemgetter('filesize') ) #根据文件大小进行排序
print tuplist
tuplist.sort(key=operator.itemgetter('filename') ) #根据文件名称进行排序
print tuplist
3.sqlite数据库操作,做了个简单的select操作。
__author__ = 'xuqiang'
import sqlite3
cx = sqlite3.connect("btopp.db")
cu=cx.cursor()
cu.execute("select * from btopp")
print cu.fetchall()
参考资料:http://www.jb51.net/article/65792.htm Python遍历指定文件及文件夹的方法
http://coolshell.cn/articles/4990.html 程序员技术练级攻略
Python基础练习的更多相关文章
- python之最强王者(2)——python基础语法
背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...
- Python开发【第二篇】:Python基础知识
Python基础知识 一.初识基本数据类型 类型: int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位 ...
- Python小白的发展之路之Python基础(一)
Python基础部分1: 1.Python简介 2.Python 2 or 3,两者的主要区别 3.Python解释器 4.安装Python 5.第一个Python程序 Hello World 6.P ...
- Python之路3【第一篇】Python基础
本节内容 Python简介 Python安装 第一个Python程序 编程语言的分类 Python简介 1.Python的由来 python的创始人为吉多·范罗苏姆(Guido van Rossum) ...
- 进击的Python【第三章】:Python基础(三)
Python基础(三) 本章内容 集合的概念与操作 文件的操作 函数的特点与用法 参数与局部变量 return返回值的概念 递归的基本含义 函数式编程介绍 高阶函数的概念 一.集合的概念与操作 集合( ...
- 进击的Python【第二章】:Python基础(二)
Python基础(二) 本章内容 数据类型 数据运算 列表与元组的基本操作 字典的基本操作 字符编码与转码 模块初探 练习:购物车程序 一.数据类型 Python有五个标准的数据类型: Numbers ...
- Python之路【第一篇】python基础
一.python开发 1.开发: 1)高级语言:python .Java .PHP. C# Go ruby c++ ===>字节码 2)低级语言:c .汇编 2.语言之间的对比: 1)py ...
- python基础之day1
Python 简介 Python是著名的“龟叔”Guido van Rossum在1989年圣诞节期间,为了打发无聊的圣诞节而编写的一个编程语言. Python为我们提供了非常完善的基础代码库,覆盖了 ...
- python基础之文件读写
python基础之文件读写 本节内容 os模块中文件以及目录的一些方法 文件的操作 目录的操作 1.os模块中文件以及目录的一些方法 python操作文件以及目录可以使用os模块的一些方法如下: 得到 ...
- python基础之编码问题
python基础之编码问题 本节内容 字符串编码问题由来 字符串编码解决方案 1.字符串编码问题由来 由于字符串编码是从ascii--->unicode--->utf-8(utf-16和u ...
随机推荐
- ECharts 是一款开源
ECharts
- Python自动化运维之18、Python操作 MySQL、pymysql、SQLAchemy
一.MySQL 1.概述 什么是数据库 ? 答:数据的仓库,和Excel表中的行和列是差不多的,只是有各种约束和不同数据类型的表格 什么是 MySQL.Oracle.SQLite.Access.MS ...
- django+nginx+supervisor+gunicorn+gevent 网站部署
django+nginx+supervisor+gunicorn+gevent 网站部署 django,nginx,supervisor,gunicorn,gevent这几个都是在本领域大名鼎鼎的软件 ...
- Node.js模块 加载笔记
//核心模块就是Node.js标准API种提供的模块,如fs,http,net.vm等.官方提供,编译成二进制代码//核心模块拥有最高的加载优先级 //文件模块则是存储为单独的文件(或文件夹)的模块, ...
- matplotlib绘制精美的图表(这是教程哦)
http://sebug.net/paper/books/scipydoc/matplotlib_intro.html
- JSP前端总结
一.C标签 一] <c:out value="..." default="..." escapeXml="true"> ...
- 14.2 InnoDB and the ACID Model
14.2 InnoDB and the ACID Model ACID 模型是一组数据库设计原则,强调可靠性方面对于商业数据和关键人物. MySQL 包含组件比如InnoDB存储引擎坚持ACID 模型 ...
- COJ 0332 The Flash
传送门:http://oj.cnuschool.org.cn/oj/home/problem.htm?problemID=302 The Flash 难度级别:B: 运行时间限制:1000ms: 运行 ...
- Hadoop MapReduce InputFormat/OutputFormat
InputFormat import java.io.IOException; import java.util.List; /** * InputFormat describes the input ...
- Windows 7 中未能从程序集System.ServiceModel
Windows 7 中未能从程序集System.ServiceModel “/”应用程序中的服务器错误. 未能从程序集“System.ServiceModel, Version=3.0.0.0 ...