一. python 文件读取
1. 基本操作
读取文件信息时要注意文件编码, 文件编码有 UFT-8,ASCII 或 UTF-16 等.
不过在 python 中最为常用的是 UTF-8, 所以如果不特别说明就默认 UTF-8 编码.
读取文件可以使用 rt 模式下的 open() 函数, 示例如下:
- # 以字符串的形式读取一个文件
- with open('somefile.txt', 'rt') as f:
- data = f.read()
- with open('somefile.txt', 'rt') as f:
- for line in file: #逐行处理数据
- #prossce line
2. 文件与路径
文件有两个关键属性:"文件名"(通常写成一个单词) 和 "路径". 路径指明了文件在计算机上的位置.
例如, 我的 Windows 10 笔记本上有一个文件名为 projects.docx, 它的路径在 C:\Users\Documents. 文件名中, 最后一个句点之后的部分称为文件的 "扩展名", 它指出了文件的类型. project.docx 是一个 Word 文档, Users 和 Documents 都是指 "文件夹"(也成为目录).
有两种方法指定一个文件路径.
• "绝对路径", 总是从根文件夹开始.
• "相对路径", 它相对于程序的当前工作目录.(少用)
- #-*-encoding:uft-8-*-
- import os
- os.path.abs('C:\\user\\soft\\python') #绝对路径
- os.ispath('C:..\\python') #相对路径
只有用绝对路径操作
- # 交互模式下
- >>> import os
- >>> path = '/Users/beazley/Data/data.csv'
- >>> # Get the last component of the path
- >>> os.path.basename(path)
- 'data.csv'
- >>> # Get the directory name
- >>> os.path.dirname(path)
- '/Users/beazley/Data'
- >>> # Join path components together
- >>> os.path.join('tmp', 'data', os.path.basename(path))
- 'tmp/data/data.csv'
- >>> # Expand the user's home directory
- >>> path = '~/Data/data.csv'
- >>> os.path.expanduser(path)
- '/Users/beazley/Data/data.csv'
- >>> # Split the file extension
- >>> os.path.splitext(path)
- ('~/Data/data', '.csv')
- >>>
来源: http://www.bubuko.com/infodetail-3041197.html