免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 14170 | 回复: 7
打印 上一主题 下一主题

如何读取文件,并把数据存到二维数组中? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-05-23 05:10 |只看该作者 |倒序浏览

假设有个文件,形式如下:

     1.1
     0.1
     0.2
     0.3
     0.4

     2.4  
     3.3
     2.5
     1.3
     4.5

     3.6
     8.1
     9.8
     5.6
     3.1

有3组,每组5个数,要求外循环三次,内循环5次,把整个数组存到一个5行3列的2维数组中。

论坛徽章:
0
2 [报告]
发表于 2012-05-23 09:54 |只看该作者
本帖最后由 anonymous0502 于 2012-05-23 10:02 编辑
  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. from pprint import pprint
  4. vbuf=open('/tmp/1.txt','r').read().split('\n\n')
  5. result=zip(*[x.strip().split('\n') for x in vbuf])
  6. pprint(result)
复制代码

论坛徽章:
0
3 [报告]
发表于 2012-05-23 16:13 |只看该作者
非常感谢楼上的回复。

论坛徽章:
0
4 [报告]
发表于 2012-05-24 06:58 |只看该作者
回复 2# anonymous0502


首先感谢您的回复,引申的问题是如果这三组数据是连在一起的,也就是他们彼此之间没有空行,该如何处理呢?   

论坛徽章:
0
5 [报告]
发表于 2012-05-24 09:23 |只看该作者
本帖最后由 anonymous0502 于 2012-05-24 09:29 编辑
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-

  3. import sys
  4. from pprint import pprint


  5. def myprint(obj, end='\n'):
  6.     sys.stdout.write(str(obj) + end)


  7. def loadtxtintotable(fname, rows, skipemptyline=False):
  8.     result = [list() for i in range(rows)]
  9.     i = 0
  10.     with open(fname, 'r') as f:
  11.         while True:
  12.             line = f.readline()
  13.             if not line:
  14.                 break
  15.             if skipemptyline and line.strip() == '':
  16.                 continue
  17.             result[i % rows].append(line.strip())
  18.             i += 1
  19.     return result


  20. def main():
  21.     fname = 'c:/temp/1.txt'
  22.     rows = 5
  23.     skipemptyline = True
  24.     tablerows = loadtxtintotable(fname, rows, skipemptyline)
  25.     pprint(tablerows)


  26. if __name__ == '__main__':
  27.     main()
  28.     myprint('done')
复制代码

论坛徽章:
0
6 [报告]
发表于 2012-05-24 15:28 |只看该作者
回复 5# anonymous0502


   早上起来就看到了回复,向您学习。

论坛徽章:
0
7 [报告]
发表于 2012-05-24 15:34 |只看该作者
我也是python新手,共同进步

论坛徽章:
0
8 [报告]
发表于 2012-05-25 08:05 |只看该作者
回复 7# anonymous0502
无名胜有名!
神码!:wink:


   
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP