问题一:如何读写csv数据?
我们获得了雅虎网站平安银行2017年的股市信息,以csv数据格式存储:
Date,Open,High,Low,Close,Volume,Adj Close
2017/4/24,8.97,8.98,8.89,8.93,39499500,8.93
2017/4/21,8.92,8.99,8.9,8.97,32540800,8.97
2017/4/20,8.9,8.94,8.89,8.92,43763000,8.92
2017/4/19,9.03,9.04,8.9,8.91,79966800,8.91
2017/4/18,9.09,9.1,9.05,9.05,33537600,9.05
2017/4/17,9.08,9.11,9.05,9.1,53189200,9.1
2017/4/14,9.11,9.12,9.06,9.08,49050000,9.08
2017/4/13,9.11,9.14,9.1,9.12,35744200,9.12
2017/4/12,9.16,9.17,9.1,9.12,45533600,9.12
现将交易中成交量超过50000000的记录存储到另一个csv文件中。
解决方案:
使用标准库中的csv模块,可以使用其中reader和writer完成csv文件读写。
In [1]: import csv
In [2]: csv.reader?
Docstring:
csv_reader = reader(iterable [, dialect='excel']
[optional keyword args])
for row in csv_reader:
process(row)
The "iterable" argument can be any object that returns a line
of input for each iteration, such as a file object or a list. The
optional "dialect" parameter is discussed below. The function
also accepts optional keyword arguments which override settings
provided by the dialect.
The returned object is an iterator. Each iteration returns a row
of the CSV file (which can span multiple input lines).
Type: builtin_function_or_method
In [3]: csv.writer?
Docstring:
csv_writer = csv.writer(fileobj [, dialect='excel']
[optional keyword args])
for row in sequence:
csv_writer.writerow(row)
[or]
csv_writer = csv.writer(fileobj [, dialect='excel']
[optional keyword args])
csv_writer.writerows(rows)
The "fileobj" argument can be any object that supports the file API.
Type: builtin_function_or_method
使用writer()和reader()函数,操作csv文件
In [3]: with open('tab.csv','rt') as fin:
...: cin = csv.reader(fin)
...: values = [ row for row in cin]
...:
In [4]: values[0]
Out[4]: ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
In [5]: values = values[1:]
In [6]: values[0][5]
Out[6]: '39499500'
In [7]: with open('tab.csv','rt') as fin:
...: cin = csv.reader(fin)
...: values = [ row for row in cin]
...: with open('tab2.csv','wt') as fin2:
...: writer = csv.writer(fin2)
...: headers = values[0]
...: writer.writerow(headers)
...: for row in values[1:]:
...: if int(row[5]) >= 50000000:
...: writer.writerow(row)
...:
In [8]: cat tab2.csv
Date,Open,High,Low,Close,Volume,Adj Close
2017/4/19,9.03,9.04,8.9,8.91,79966800,8.91
2017/4/17,9.08,9.11,9.05,9.1,53189200,9.1
2017/4/11,9.17,9.19,9.09,9.15,61243700,9.15
2017/4/7,9.19,9.22,9.17,9.2,51484400,9.2
2017/3/31,9.08,9.18,9.08,9.17,63312100,9.17
......
问题二:如何读写json数据?
问题内容:在python中如何读写json数据?
解决方案:使用标准库中的json模块,其中loads,dumps函数可以完成json数据的读写。
In [1]: import json
In [2]: json.
json.decoder json.encoder json.JSONEncoder json.scanner
json.dump json.JSONDecodeError json.load
json.dumps json.JSONDecoder json.loads
In [2]: l = [1,2,"abc",{"age":13,"name":"Bob"}]
In [3]: json.dumps(l)
Out[3]: '[1, 2, "abc", {"age": 13, "name": "Bob"}]'
In [4]: d = {'b':None,'a':5,'c':'abc'}
In [5]: json.dumps(d)
Out[5]: '{"b": null, "a": 5, "c": "abc"}'
In [6]: json.dumps?
Signature: json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
我们发现,在生成的json串中,每个 ','后面都有一个空格,我们可以修改dumps()函数中的separators参数,指定分隔符不带空格。
In [7]: json.dumps(l,separators=[',' , ':'])
Out[7]: '[1,2,"abc",{"age":13,"name":"Bob"}]'
我们还可以对输出的结果按照键排序,通过参数sort_keys
In [8]: json.dumps(d,sort_keys=True)
Out[8]: '{"a": 5, "b": null, "c": "abc"}'
下面我们使用loads()函数将json格式转化为python中的数据格式。
In [9]: l2 = json.loads('[1, 2, "abc", {"age": 13, "name": "Bob"}]')
In [10]: l2
Out[10]: [1, 2, 'abc', {'age': 13, 'name': 'Bob'}]
In [11]: l2[0]
Out[11]: 1
In [12]: d2 = json.loads('{"b": null, "a": 5, "c": "abc"}')
In [13]: d2
Out[13]: {'a': 5, 'b': None, 'c': 'abc'}
函数load()和dump()操作的是文件:
In [14]: with open('demo.json','wt') as f:
...: json.dump(l,f)
...:
In [15]: cat demo.json
[1, 2, "abc", {"age": 13, "name": "Bob"}]
问题三:如何解析简单的xml文档?
问题内容:python中如何解析xml文档?
解决方案:使用标准库中的xml.etree.ElementTree,其中的parse函数可以解析xml文档。
In [1]: from xml.etree.ElementTree import parse
In [2]: parse?
Signature: parse(source, parser=None)
Docstring:
Parse XML document into element tree.
*source* is a filename or file object containing XML data,
*parser* is an optional parser instance defaulting to XMLParser.
Return an ElementTree instance.
File: /usr/local/lib/python3.5/xml/etree/ElementTree.py
Type: function
In [3]: f = open("demo.xml")
In [4]: et = parse(f)
In [5]: root = et.getroot()
In [6]: root
Out[6]:
In [7]: root.tag
Out[7]: 'breakfast_menu'
In [8]: root.attrib
Out[8]: {}
In [9]: root.
root.append root.findall root.getiterator root.iterfind root.remove
root.clear root.findtext root.insert root.itertext root.set
root.extend root.get root.items root.keys
root.find root.getchildren root.iter root.makeelement
我们根据上面的函数,可以操作xml数据。
find()和findall()方法只能查找当前节点的字节点,不过当我们使用iter()方法的时候,可以遍历所有子节点。
问题四:如何构建xml文档?
如何将其它文档转化为xml文旦。
解决方案:使用标准库中的xml.etree.ElementTree,构建ElementTree,使用write方法写入文件。
In [1]: from xml.etree.ElementTree import Element,ElementTree
In [2]: from xml.etree.ElementTree import tostring
tostring可以查看转化为xml格式后的样式
添加跟节点
In [3]: e = Element('Data')
In [4]: e.tag
Out[4]: 'Data'
为节点设置属性
In [5]: e.set('name','abc')
In [6]: tostring(e)
Out[6]: b''
为节点设置文本值
In [7]: e.text = '123'
In [8]: tostring(e)
Out[8]: b'123'
新增两个节点
In [9]: e2 = Element('Row')
In [10]: e3 = Element('Open')
In [11]: e3.text = '8.80'
将e3设置为e2的子节点
In [12]: e2.append(e3)
In [13]: tostring(e2)
Out[13]: b'8.80
'
In [14]: e.text = None
将e2设置为e的字节点
In [15]: e.append(e2)
In [16]: tostring(e)
Out[16]: b'8.80
'
创建ElementTree元素用于写入文件,传入的参数是根元素
In [17]: et = ElementTree(e)
使用write()函数,将字符串写入到文件
In [18]: et.write('demo2.xml')
In [19]: cat demo2.xml
8.80
我们将之前的股票交易转化为xml格式:
In [50]: from xml.etree.ElementTree import Element,ElementTree
In [51]: import csv
该函数将输出的xml格式规范化
In [52]: def pretty(e,level=0):
...: if len(e) > 0:
...: e.text = '\n' + '\t' * (level + 1)
...: for child in e :
...: pretty(child,level + 1)
...: child.tail = child.tail[:-1]
...: e.tail = '\n' + '\t' * level
...:
In [53]: def csvToXml(fname):
...: with open(fname,'rt') as f :
...: reader = csv.reader(f)
...: values = [ row for row in reader]
...: headers = values[0]
...: root = Element('Data')
...: for row in values[1:]:
...: eRow = Element('Row')
...: root.append(eRow)
...: for tag , text in zip(headers,row):
...: e = Element(tag)
...: e.text = text
...: eRow.append(e)
...: pretty(root)
...: return ElementTree(root)
...:
In [54]: et = csvToXml('tab.csv')
In [55]: et.write("pay.xml")
问题五:如何读写excel文件
问题内容:数据格式为xls,xlsx,是一种常用的电子表格。小学某班级成绩,记录在excel文件中:
姓名 语文 数学 外语
李磊 95 99 96
韩梅 98 100 93
张峰 94 95 95
......
利用python读写excel,添加“总分”列,计算每人总分。
解决方案:
使用第三方库xlrd和xlwt,这两个库分别用于excel读和写。
之后有时间补充该内容:
相关之前的文章http://www.jianshu.com/p/32d6b528d5c5