Python文件数据记录存储与处理


 本节主要讨论Python下如何通过文件操作实现对数据记录集的存储与处理的操作方法。

     在Python里和其他高级语言一样可以通过文件读写将一些记录集写入文件或者通过文件读操作从文件里读取一条或多条和数据记录集,我们知道记录集recordset是由一个个的数据字段组成的。

 \
 


     上图,Record里由三个字段组成name、id、job。文件里可以存储多条记录,如下图所示:

 \
 


       像这样的数据结构record在Python里该怎样处理呢?很简单,记录有几个字段就读或者写几次然后结束一条记录的读写操作,下面我们先看看如何写入一条数据记录呢?之后我们在看看如何读一条记录。

       1. 往文件里写入记录


 

n = input("How many employees records do you want to create? ") 
wr = open("b.txt", 'w') 
for x in range(1, n + 1): 
  id = str(raw_input("Plz input your Id: ")) 
  wr.write(id+'\n') 
  name = raw_input("Plz input your name: ") 
  wr.write(name+'\n') 
  job = raw_input("Plz input your job: ") 
  wr.write(job+'\n') 
wr.close() 

n = input("How many employees records do you want to create? ")
wr = open("b.txt", 'w')
for x in range(1, n + 1):
  id = str(raw_input("Plz input your Id: "))
  wr.write(id+'\n')
  name = raw_input("Plz input your name: ")
  wr.write(name+'\n')
  job = raw_input("Plz input your job: ")
  wr.write(job+'\n')
wr.close()


       程序运行过程如下:

 

 

>>>  
How many employees records do you want to create? 3 
Plz input your Id: 101 
Plz input your name: jeapedu 
Plz input your job: eng 
Plz input your Id: 102 
Plz input your name: jeapedu 
Plz input your job: tec 
Plz input your Id: 103 
Plz input your name: jeapedu 
Plz input your job: fae 
>>>  

>>>
How many employees records do you want to create? 3
Plz input your Id: 101
Plz input your name: jeapedu
Plz input your job: eng
Plz input your Id: 102
Plz input your name: jeapedu
Plz input your job: tec
Plz input your Id: 103
Plz input your name: jeapedu
Plz input your job: fae
>>>

       程序运行结果如下:

 \
 


       2. 从文件里读取记录

       由于数据记录是由三个字段组成,故在while循环体内需要读取三次,可完成每条记录的三个字段的读取操作,程序代码如下所示:


 

 rr = open("b.txt", 'r') 
 
id = rr.readline() 
id = id.rstrip('\n') 
 
while id != "": 
  print id, 
  name = rr.readline() 
  name = name.rstrip('\n') 
  print name, 
  job = rr.readline() 
  job = job.rstrip('\n') 
  print job 
  id = rr.readline() 
  id = id.rstrip('\n') 
print "read finish!" 
rr.close() 

rr = open("b.txt", 'r')

id = rr.readline()
id = id.rstrip('\n')

while id != "":
  print id,
  name = rr.readline()
  name = name.rstrip('\n')
  print name,
  job = rr.readline()
  job = job.rstrip('\n')
  print job
  id = rr.readline()
  id = id.rstrip('\n')
print "read finish!"
rr.close()

       运行结果如下所示:

 >>>  
101 jeapedu eng 
102 jeapedu tec 
103 jeapedu fae 
read finish! 
>>>  

>>>
101 jeapedu eng
102 jeapedu tec
103 jeapedu fae
read finish!
>>>

 


-->

 

相关内容

    暂无相关文章

评论关闭