python islice_python文件操作细节
python文件讀寫示例
with open(file_w_path, 'r') as f_r:
with open(file_r_path, 'w') as f_w:
for line in f_r.readlines():
f_w.write(line + '\n')
覆蓋和追加細節
r:只讀方式打開文件,缺省默認。
r+:讀寫方式打開文件。
w:只寫方式打開文件,若文件存在以覆蓋方式寫入,不存在則創建該文件(注意目錄無法創建,即指定文件位置的目錄不存在會報錯)
w+:讀寫方式代開文件,文件存在則覆蓋寫入。
a:追加方式打開文件,文件指針會放在文件結尾。
a+:追加讀寫。
python三種讀取文件方式:
read()
readline()
readlines()
然而它們的區別是什么呢,在平時用到時總會遇到,今天總結一下。
0. 前期工作
首先新建一個文件read.txt,用于實際效果舉例
Hello
welcome to my world
you are so clever !!!
1. read()
read(size)方法從文件當前位置起讀取size個字節,默認(無參數)表示讀取至文件結束為止,它的返回為字符串對象
測試程序如下:
import os
with open(os.path.join(os.getcwd(), 'read.txt')) as f:
content = f.read()
print(content)
print(type(content))
這里需要注意兩點:
我用到了os相關操作,即省去了需要輸入文件完整路徑的麻煩。
大家要養成with open file as f: 這一習慣,即操作完畢后讓其自動關閉文件。
Hello
welcome to my world
you are so clever !!!
Process finished with exit code 0
2. readline()
每次只讀一行內容,讀取時內存占用較少(適用于大文件),它的返回為字符串對象
測試程序:
import os
with open(os.path.join(os.getcwd(), 'read.txt')) as f:
while True:
line = f.readline()
if line:
print(line)
else:
break
輸出結果:
Hello
Process finished with exit code 0
3. readlines()
讀取文件所有行,保存在列表(list)變量中,列表中每一行為一個元素,它返回的是一個列表對象。
測試程序:
import os
with open(os.path.join(os.getcwd(), 'read.txt')) as f:
content = f.readlines()
print(content)
print(type(content))
輸出結果:
['Hello\n', 'welcome to my world\n', '1234\n', 'you are so clever !!!']
Process finished with exit code 0
seek
用于移動文件讀取指針到指定位置
itertools.islice()
直接讀取文件制定行
#讀取文件前50行
for line in itertools.islice(f, 50):
pass
#跳過文件第一行讀取文件
for line in itertools.islice(f, 1, None):
pass
總結
以上是生活随笔為你收集整理的python islice_python文件操作细节的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: yolov4论文_YOLOv4论文详细解
- 下一篇: 怎么添加本地音乐_展示 | 传一学员优秀