1. 读取文本文件代码:
- f = open(‘test.txt’, ‘r’)
- print f.read()
- f.seek(0)
- print f.read(14)
- f.seek(0)
- print f.readline()
- print f.readline()
- f.seek(0)
- print f.readlines()
- f.seek(0)
- for line in f:
- print line,
- f.close()
运行结果:root@he-desktop:~/python/example# python read_txt.py 第一行第二行第三行 第一行第第一行 第二行 [‘\xe7\xac\xac\xe4\xb8\x80\xe8\xa1\x8c\n’, ‘\xe7\xac\xac\xe4\xba\x8c\xe8\xa1\x8c\n’, ‘\xe7\xac\xac\xe4\xb8\x89\xe8\xa1\x8c\n’]第一行第二行第三行 open的第二个参数:
- r,读取模式
- w,写入模式
- a,追加模式
- r+,读写模式
read()表示读取到文件尾,size表示读取大小。seek(0)表示跳到文件开始位置。readline()逐行读取文本文件。readlines()读取所有行到列表中,通过for循环可以读出数据。close()关闭文件。 2. 写入文本文件代码:
- f = open(‘test.txt’, ‘r+’)
- f.truncate()
- f.write(‘0123456789abcd’)
- f.seek(3)
- print f.read(1)
- print f.read(2)
- print f.tell()
- f.seek(3, 1)
- print f.read(1)
- f.seek(-3, 2)
- print f.read(1)
- f.close()
运行结果:root@he-desktop:~/python/example# python write_txt.py 34569b truncate()表示清空文件write()写入文本seek(3)定位到第4个元素前,0表示文件开始,也就是第1个元素前。seek(3, 1)第二个参数默认是0,表示从文件开始处读取;1表示从当前位置开始计数;2表示从文件最后开始。read(1)读取一个字节,指针会根据读取的大小移动相应的位置。tell()取得当前指针的位置。 3. 读取文件信息
- # coding: utf-8
- f = open(‘test.txt’)
- print ‘文件名:’, f.name
- print ‘是否处于关闭状态:’, f.closed
- print ‘打开的模式:’, f.mode
运行结果:root@he-desktop:~/python/example# python read_info.py 文件名: test.txt是否处于关闭状态: False打开的模式: r