hyytaojunming 发表于 2017-4-25 12:05:40

Python 学习系列(四)

这篇文章继续介绍Python的IO内建函数,下面是我做的一个Sample:
'''
Created on 2010-4-4
@author: Jamson Huang
'''
#解析字符串函数以及IO函数
import sys
#import os
import math
if __name__ == '__main__':
#gloabal zone   
a = 5
count = 0
tempStr = ['homework','something', 'python','jamson']
tempZip = ['Children', 'do', 'Male', 'user']
myDicts = {('China','Hubei'):('yourName','Jamson')}
tempTable = {'china':86,'singpore':65}
globalStr = 'python is loved language!'
filePath = 'C:/python/mylog.txt'
#string function
#注意:当全局变量和局部变量相同时,会出现error:UnboundLocalError
def strFunc():
print('repr():', repr(globalStr))
print('repr():', repr(0.1))
print(globalStr.zfill(50))
print('we are the {0} who says {1}'.format('chinese', 'chinese'))
print('The value of PI is approximately {0:.4f}'.format(math.pi))
for countryStr,zipStr in tempTable.items():
print('{0:10}=>{1:10d}'.format(countryStr, zipStr))
tempTable1 = {'china':'jamson', 'singapore':'Liew Sig'}
for countryStr,personStr in tempTable1.items():
print('{0:10}=>{1:s}'.format(countryStr, personStr))
myFile = open(filePath,'r')
for line in myFile:
print(line, end='')
strFunc()
#readline 和readlines的不同
#tell():方法返回一个指代文件对象当前位置的整数,表示从文件开头到当前位置的字节数。   
#seek(offset, from_what):新的位置是通过将 offset 值与参考点相加计算得来的,
#    参考点是由 from_what 参数确定的。 如果 from_what 值为0则代表从文件头开始计算,
#    值为1时代表从当前文件位置开始计算,值为2时代表从文件尾开始计算。 from_what 参数
#    可以省略并且其默认值为0,即使用文件头作为参考点      
def fileIoFunc():
myFile = open(filePath,'rb+')
print(myFile.readline())#注意大小写
print(myFile.tell())
print(myFile.seek(10))
print(myFile.tell())
print(myFile.seek(11,1))
print(myFile.tell())
#      print(myFile.size())
#      print(myFile.readlines())
myFile.close()
#      myFile.read()
try:
myFile.read()
except ValueError:
print(sys.stderr, 'IO Read Error')
finally:
print('IO read close')
#Traceback (most recent call last):
#File "<stdin>", line 1, in ?
#ValueError: I/O operation on closed file      
fileIoFunc()
#with key in file IO:这个方法在很多高级语言中都使用(如java)
#open(filename, mode)
#    通常,文件是以 text mode (文本模式)方式打开,
#    即你从文件中读写字符串都是以一种特殊编码(默认为UTF-8)进行编码的。 可以通过在常用模式后添加 'b'
#   选项从而以 binary mode (二进制模式)打开文件,现在数据就是以字节码对象形式来读写了。
#   这种模式可以用在所有非文本文件中,例如:jpeg图片。      
def withFunc():
with open(filePath, 'r') as f:
print(f.read())
f.close()
withFunc()
#pickle():pickling and unpickling
#    它几乎可以将任何Python对象(甚至是一些Python代码!)转换为字符串表示形式,这个过程称为
#    pickling (封装)。 从这个字符串表示形式中重建Python对象被称为 unpickling (拆封)。
#    在 pickling 和 unpickling 之间,字符串表示的对象可以存储在文件或数据中,
#    或者可以通过网络连接发送给远程的机器。被称为persistent 对象(持久化对象)
import pickle
def pickleFunc():
x = ''
with open(filePath, 'r') as f:
x = pickle.load(f)
print(x)
#            pickle.dump(x, f)
Run Python, Console输出结果为:
repr(): 'python is loved language!'
repr(): 0.1
0000000000000000000000000python is loved language!
we are the chinese who says chinese
The value of PI is approximately 3.1416
singpore=>      65
china   =>      86
china   =>jamson
singapore =>Liew Sig
If you do much work on computers, eventually you find that there’
s some task you’d like to automate. For example, you may wish.b'If you do much work on computers, eventually you find that there\xa1\xaf\r\n'
68
10
10
21
21
<_io.TextIOWrapper name='<stderr>' encoding='UTF-8'> IO Read Error
IO read close
If you do much work on computers, eventually you find that there’
s some task you’d like to automate. For example, you may wish.
页: [1]
查看完整版本: Python 学习系列(四)