Python-File处理

# -*- coding: utf-8 -*-
# @Time : 2017/12/7 0007 9:53
# @Author : wangyafeng
# @Email : 279949848@qq.com

'''
readline.read(size) Read at most n characters from stream.
'''
readline=open("d:\\abc.txt", "r") #打开一个文件
strabc1=readline.read(10) #读前10个字符
print("读取的字节:",strabc1)
readline.close()

'''
readline.readlines(size) Return a list of lines from the stream. 这个size指的是缓冲区
'''
readline=open("d:\\abc.txt", "r") #打开一个文件
strabc2=readline.readlines(1)
print("读取第一行:",strabc2)
readline.close()

'''
readline Read until newline or EOF.
'''

readline=open("d:\\abc.txt", "r") #打开一个文件
strabc3=readline.readline(10)
print("readline:",strabc3)
readline.close()

# help(readline)

'''
iter:使用迭代器进行读取文件
'''
readline=open("d:\\abc.txt", "r") #打开一个文件
iter_r=iter(readline)
lines=0
for line in iter_r:
lines+=1
print(lines)
print(readline.readline())

readline.close()


readline=open("d:\\abc.txt", "r") #打开一个文件
strabc=readline.read(10) #读前10个字符
print(strabc) #打印取出的字符

position=readline.tell() #定位当前位置
print("当前游标位置",position)

position=readline.seek(0,0) #游标重新定位到文件开头 seek(offset [,from])方法改变当前文件的位置
strabc2=readline.readline()
print(strabc2)
readline.close()

[root@localhost pythontest]# python
Python 3.6.2 (default, Dec 7 2017, 09:40:15)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> read=open('wyfstu.txt','r')
>>> import os
>>> read.tell()
0
>>> read.readline(10)
'1233412334'
>>> read.tell()
10
>>> read.seek(0,0)
0
>>> read.tell()
0



posted @ 2017-12-07 13:47  王亚锋  阅读(208)  评论(0编辑  收藏  举报