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 ...
随机推荐
- git branch分支管理用法总结
查看分支(远程和本地) 1 查看本地分支: $ git branch 2 查看远程分支: $ git branch -r 3.查看本地和远程分支 $ git branch -a 创建分支 1.创建本地 ...
- Python报错:SyntaxError: Non-ASCII character '\xe5' in file的解决方法
SyntaxError: Non-ASCII character '\xe5' in file 原因:Python默认是以ASCII作为编码方式的,如果在自己的Python源码中包含了中文(或者其他的 ...
- HDU1372:Knight Moves(经典BFS题)
HDU1372:Knight Moves(BFS) Time Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld & %l ...
- insert 和 if x is not None
insert(位置,元素) #!/usr/bin/python aList = [123, 'xyz', 'zara', 'abc'] aList.insert( 3, 2009) print &qu ...
- Maven插件开发
Maven为我们提供了丰富的插件资源,使得开发调试过程中非常方便,可以满足大多数场景下的需求.当然有时候,我们也需要根据需求定制自己的插件.下面是在开发Maven插件时的一点备忘录,具体的开发流程请G ...
- 转:Google论文之三----MapReduce
文章来自于:http://www.cnblogs.com/geekma/p/3139823.html MapReduce:大型集群上的简单数据处理 摘要 MapReduce是一个设计模型,也是一个处理 ...
- poj Monthly Expense
http://poj.org/problem?id=3273 #include<cstdio> #include<cstring> #include<cmath> ...
- MYSQL主从同步测试
参考: http://www.cnblogs.com/zgx/archive/2011/09/13/2174823.html 注意选建同步用户,其它的都按步就搬. 还有,不要让IPTABLES坏事,开 ...
- 如何让Qt 的程序等待一段时间(等待的同时,还让主界面刷新图片)good
后面这种方法可以不影响其他线程的响应,又可以达到等待的目的. 测试的一个小例子: class Widget : public QWidget { Q_OBJECT public: Widget(QWi ...
- OpenGl学习总结
http://wenku.baidu.com/view/5305fe4f866fb84ae45c8dcd.html