[Python]读写文件方法
2023-09-27 14:24:26 时间
http://www.cnblogs.com/lovebread/archive/2009/12/24/1631108.html
http://www.cnblogs.com/xuxn/archive/2011/07/27/read-a-file-with-python.html
Python按行读文件
1. 最基本的读文件方法: # File: readline-example-1.py file = open("sample.txt") while 1: line = file.readline() if not line: break pass # do something 一行一行得从文件读数据,显然比较慢;不过很省内存。 在我的机器上读10M的sample.txt文件,每秒大约读32000行 2. 用fileinput模块 # File: readline-example-2.py import fileinput for line in fileinput.input("sample.txt"): pass 写法简单一些,不过测试以后发现每秒只能读13000行数据,效率比上一种方法慢了两倍多…… 3. 带缓存的文件读取 # File: readline-example-3.py file = open("sample.txt") while 1: lines = file.readlines(100000) if not lines: break for line in lines: pass # do something 这个方法真的更好吗?事实证明,用同样的数据测试,它每秒可以读96900行数据!效率是第一种方法的3倍,第二种方法的7倍! ———————————————————————————————————————————————————————————— 在Python 2.2以后,我们可以直接对一个file对象使用for循环读每行数据: # File: readline-example-5.py file = open("sample.txt") for line in file: pass # do something 而在Python 2.1里,你只能用xreadlines迭代器来实现: # File: readline-example-4.py file = open("sample.txt") for line in file.xreadlines(): pass # do something
http://www.cnblogs.com/xuxn/archive/2011/07/27/read-a-file-with-python.html
http://blog.csdn.net/cashey1991/article/details/7003109 python获取文件及文件夹大小 @1.获取文件大小 使用os.path.getsize函数,参数是文件的路径。 @2.获取文件夹大小,即遍历文件夹,将所有文件大小加和。遍历文件夹使用os.walk函数 import os from os.path import join, getsize def getdirsize(dir): size = 0L for root, dirs, files in os.walk(dir): size += sum([getsize(join(root, name)) for name in files]) return size if '__name__' == '__main__': filesize = getdirsize(r'c:\windows') print 'There are %.3f' % (size/1024/1024), 'Mbytes in c:\\windows'
aa
相关文章
- python tkinter-消息框、对话框、文件对话框
- Python标准库:codecs【专门做编码转换】【open()、encode()、decode()、lookup()、getencoder()】【读写文件codecs.open()优于open()】
- 【数学建模】混合整数规划MIP(Python+Gurobi代码实现)
- 用Python删除本地目录下某一时间点之前创建的文件
- python实现文件下载的方法总结
- python文件之间变量和函数的 获取/调用 的方法
- selenium-python读取XML文件
- python的re模块一些方法 && Tkinter图形界面设计 && 终止python运行函数 && python读写文件 && python一旦给字符串赋值就不能单独改变某个字符,除非重新给变量赋值
- 使用python扫描文件夹获取所有文件路径
- 第9.13节 Python文件操作总结
- 第9.1节 Python的文件打开函数open简介
- Python OS 文件/目录方法
- Python 读写文件通用工具函数方法
- Python判断文件是否存在的三种方法
- python下载文件只要一句话
- Python 中对文件的输入输出
- 使用Python删除Windows中只读文件
- shell - shell中执行python文件,并将执行结果赋值给shell变量,并对该变量进行判断(以及shell记录日志,写入.log文件)