python处理文本

检查文本行数

len(open('/path/and/filename').readlines())

参考 number of lines in a file

检查文件是否为空

>>> import os
>>> os.stat("file").st_size == 0
True

注意st_size是检查文件的大小是否为零来判断文件是否为空,这种方法不适合/proc文件系统,因为在/proc/sys文件系统中所有文件的大小都是0,则需要通过计算文件内容来判断。

参考 python how to check file empty or not

检查文件大小

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L

参考 How to check file size in python?

文件合并

python合并文件的方法需要考虑文件大小,略有不同

  • 大文件合并

  • 小文件合并

参考 Python concatenate text files

偷懒一些的方法是直接使用操作系统命令

glob模块处理Unix风格路径文件匹配

glob 是一个通过使用Unix shell来查找符合特定规则的所有路径名字。它是通过使用 os.listdir()fnmatch.fnmatch() 功能来实现,不需要调用子shell。

则返回

参考

列出目录下文件

os.listdir() 可以获取目录下的文件和子目录

如果只是文件,可以使用 os.path

如果使用 os.walk() 则会将访问的每个目录分为两个列表,分别是文件和目录。

参考 How to list all files of a directory in Python

文件读取到字典

对于需要分析数据,将数据读取到字典中非常方便索引

参考 Python - file to dictionary?

参考 How to read file into dictionary in Python specific filetype

类型

想从一个函数返回结果写入到文件

提示报错

改进

Last updated

Was this helpful?