對文件操作流程如下: 1、打開文件,得到一個文件句柄並賦給一個變數 2、通過文件句柄對文件進行操作 3、關閉文件 4、為了必免打開文件忘記關閉,可以通過上下文管理,即: with open("F:\yesterday2","r",encoding="utf-8") as f: for line in ...
對文件操作流程如下:
1、打開文件,得到一個文件句柄並賦給一個變數
2、通過文件句柄對文件進行操作
3、關閉文件
4、為了必免打開文件忘記關閉,可以通過上下文管理,即:
with open("F:\yesterday2","r",encoding="utf-8") as f:
for line in f:
print(line)
f = open("F:\yesterday2","r",encoding="utf-8")
st = f.readline()
print(st)
f.close()
print("-------------------")
f1 = open("F:\yesterday2","r",encoding="utf-8")
data = f1.read()
print(data)
print("-------------------")
f = open("F:\yesterday2","r",encoding="utf-8") # 返回一個文件對象
line = f.readline() # 調用文件的 readline()方法
while line:
print(line, end = '') # 在 Python 3 中使用
line = f.readline()
f.close()
f = open("F:\yesterday2","r",encoding="utf-8")
for i in range(5):
print(f.readline(),end="")
f.close()
print("-------------------")
f = open("F:\yesterday2","r",encoding="utf-8")
lines = f.readlines() #讀取全部內容 ,並以列表方式返回
for index,line in enumerate(lines):
print(index,line, end='') # 在 Python 3 中使用
f.close()
print("-------------------")
f =open("F:\yesterday2","r",encoding="utf-8")
w = open("F:\yesterday","w",encoding="utf-8")
line = f.readline()
while line:
w.write(line)
line = f.readline()
f.close()
w.close()
f = open("F:\yesterday2","r",encoding="utf-8")
for line in f:
print(line)