python文件操作
Python文件操作流程
1、打开文件,获取文件句柄。
2、通过句柄对文件进行操作。
2、关闭文件。
例如:
file = open(u"小重山",'r',encoding='utf-8') #打开文件,获取文件句柄。
data = file.read() #读取文件。
for i in file:
print(i.strip())
file.close()
文件打开模式
===================================================================
character meaning
---------------------------------------------------------------------------------------------------------------------
'r' open for reading(default)
'w' open for writing,truncating the file first
'x' creat a new file and open it for writing
'a' open for writing,appending to end of the file if it exists
'b' binary mode
't' text mode(default)
'+' open a disk file for updating(reading and writing)
'u' universal newline mode(deprecated)
===================================================================
文件操作方法:
遍历文件方法
number = 0
for i in file: #for内部将file对象做成一个迭代器,利用迭代器进行遍历,节省内存,效率极高。
number += 1
if number == 6:
i = "".join([i.strip(),"注:瑶琴(用美玉装饰的琴,一种贵重的乐器:瑶琴一曲寄深情。)"])
print(i.strip())
file.close()
#tell()方法:检测光标当前位置。
print(file.tell())#0
print(file.read(2))#昨夜
print(file.tell())#6 说明一个中文占3个字符。
#seek()方法:调整光标位置的方法。
file.seek(0)#将光标移到文件的开头

浙公网安备 33010602011771号