您的位置:首页 > 编程语言 > Python开发

python 文件处理模块的使用,如何读取文件中数据

2015-10-28 02:37 1066 查看
------------------------------cal.txt文件原始内容---------------------------------
1 he 25 15213233036 7352342341
2 xc 23 18301111956 127655339
3 yy 22 18512222422 605322544
4 xw 22 18739999676 1693324254
5 xl 24 13698888179 542343566
6 jz 23 18237777012 876546465
7 sj 24 18506666832 445355433
8 dc 32 15995555636 4343435533
9 ccf 22 15294444335 803123121
10 fst 29 15713333535 9931231136
11 gns 30 18612222786 721313128
12 fd 23 15032222157 135321311
13 wzz 21 18739111870 519111133
14 gzc 22 15933333510 762333221
15 cys 24 18211112213 943442221

------------------------首先是加载一个文件到内存中--------------------------->>> cal = file('cal.txt')
//OK,加载一个名为cal.txt的文件,并且赋值给变量为cal
------------------------读取文件中的数据--------------------------------------
一次性读取该文件中所有内容:(读取所有值后,内存中的数据将不存在,需要重新加载到内存中)
>>> cal.read()
'1\the\t25\t15213233036\t7352342341\n2\txc\t23\t18301111956\t127655339\n3\tyy\t22\t18512222422\t605322544\n4\txw\t22\t18739999676\t1693324254\n5\txl\t24\t13698888179\t542343566\n6\tjz\t23\t18237777012\t876546465\n7\tsj\t24\t18506666832\t445355433\n8\tdc\t32\t15995555636\t4343435533\n9\tccf\t22\t15294444335\t803123121\n10\tfst\t29\t15713333535\t9931231136\n11\tgns\t30\t18612222786\t721313128\n12\tfd\t23\t15032222157\t135321311\n13\twzz\t21\t18739111870\t519111133\n14\tgzc\t22\t15933333510\t762333221\n15\tcys\t24\t18211112213\t943442221\n\n'
>>>

一次性读取该文件一行内容:(读取所有值后,内存中的数据将不存在,需要重新加载到内存中)
>>> cal = file('cal.txt')
>>> cal.readline()
'1\the\t25\t15213233036\t7352342341\n'
>>> cal.readline()
'2\txc\t23\t18301111956\t127655339\n'
>>> cal.readline()
'3\tyy\t22\t18512222422\t605322544\n'
>>> ---------------------------------------关闭读入内存中的文件-------------------------------------
>>> cal.close()
>>>
>>> cal.readline()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息