数据加载、储存与文件格式
在python中进行文件读写的简要操作:
一个简单例子
只用四行代码就可以来一个处理文件,展现了python代码的易读性:
for
line in open("file.txt"):
for word in line.split(): # split a line into
words
if word.endswith('ing'): # every variable
is an entity that has certain defined attributes
and methods
print word |
读取数据
* read_csv Load delimited data from a file,
URL, or file-like object. Use comma as default
delimiter
* read_table Load delimited data from a file,
URL, or file-like object. Use tab ('\t') as
default delimiter
* read_fwf Read data in fixed-width column
format (that is, no delimiters)
* read_clipboard Version of read_table that
reads data from the clipboard. Useful for
converting tables from web pages |
文档操作
打开一个test.txt文件 f = open('test.text','w')
用urllib模块下载到本地文件夹
下载单个文件到本地文件夹:
#下载网页文件到本地文件夹
import os,urllib2,urllib
#设置下载后存放的存储路径'C:\Users\pc\Desktop\Python code'
path=r'C:\Users\pc\Desktop\Python code'
file_name=r'MSFT.csv' #文件名,包含文件格式
dest_dir=os.path.join(path,file_name)
#设置下载链接的路径
url="'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s &y=0&g=%s&ignore=.csv"
#定义下载函数downLoadPicFromURL(本地文件夹,网页URL)
def downLoadPicFromURL(dest_dir,URL):
try:
urllib.urlretrieve(url , dest_dir)
except:
print '\tError retrieving the URL:', dest_dir
#运行
downLoadPicFromURL(dest_dir,url) |
2、下载多个文件到本地文件夹
import
os,urllib2,urllib
import re,urllib2
def getPage(url):
'''''下载文件html代码,找出一楼的核心代码'''
opener = urllib2.build_opener()
#不加头信息则出现403错误和乱码
opener.addheaders = [('User-agent', 'Mozilla/5.0')];
htmlAll = opener.open( url ).read()
reg1Floor = '<div class="msgfont">(.*?)</div>'
html = re.search(reg1Floor,htmlAll)
html = html.group()
#文件保存编码和文件编辑编码都是utf-8,所以decode一次,不然会出现乱码,但是不影响结果。
return html.decode('utf-8')
def getImg(url):
'''''从核心代码中照图图片地址,并且下载保存、命名'''
pageHtml = getPage(url)
#找到所有图片地址
regImg = '<img src="(.*?)" alt=""
/>'
imglist = re.findall(regImg,pageHtml)
dir = r'E:\img'
#print imglist
for index in xrange(0,len(imglist)):
picname = str(index+1) + '.jpg'
finename = os.path.join(dir,picname)
urllib.urlretrieve(imglist[index], finename)
print finename + ' ok!'
if __name__ == '__main__':
getImg('http://topic.csdn.net/u/20101013/11/024465A6-8E16-444C-9A09-DD374D29044C.html')
|
|
1000 次浏览 |
15次 |
|
捐助 |
|
|
|
|
|