python3基礎之文件對象操作


1.向文本文件中寫入內容

s = 'Hello world\n文本文件的讀取方法\n文本文件的寫入方法\n'
# 需要寫入文件的字符串
print('顯示需要寫入的內容:\n{0:s}'.format(s))
#-----文件操作開始------------
f = open('sample.txt', 'a+')  # 以追加(a)和讀寫(+)的模式打開並創建文件對象f
f.write(s) # 對文件對象f使用write方法
f.close()  # 關閉文件
#-----文件操作結束------------
顯示需要寫入的內容:
Hello world
文本文件的讀取方法
文本文件的寫入方法

使用上下文管理關鍵字with方法

s = 'Hello world\n文本文件的讀取方法\n文本文件的寫入方法\n'
with open('sample.txt', 'a+') as f:
    f.write(s)
with open('sample.txt','r') as src, open('sample_new.txt', 'w') as dst:
    dst.write(src.read())
with open('sample_new.txt', 'r') as fp:
    for line in fp:
        print(line)
第一個文件操作案例。Hello world

文本文件的讀取方法

文本文件的寫入方法

Hello world

文本文件的讀取方法

文本文件的寫入方法
fp.closed
True

2.讀取文件內容

fr = open('sample.txt', 'r')
print(fr.read(4))
xxx的
print(fr.read(18))
第一個文件操作案例。Hello wo
print(fr.read())
rld
文本文件的讀取方法
文本文件的寫入方法
Hello world
文本文件的讀取方法
文本文件的寫入方法
fr.close()
fr.closed
True

3.JSON知識點學習

import json
x = ['yu','bright','1','4','5']
x_bianma = json.dumps(x) # 利用json的dumps對列表x進行字符串編碼操作
x_bianma
'["yu", "bright", "1", "4", "5"]'
x_jiema = json.loads(x_bianma)
x_jiema == x # 解碼后與x相同類型
True
x_bianma == x # 編碼后與x不同類型
False
f_ = open('sample.txt', 'w')
json.dump({'a':1,'b':2,'c':3}, f_) # 對字典進行編碼並寫入文件
f_.close()

4.讀取並顯示文件所有內容

with open('sample.txt', 'r') as fp:
    while True:
        line = fp.readline()
        if not line:
            break
        print(line)
{"a": 1, "b": 2, "c": 3}
with open('sample_new.txt', 'r') as fp:
    for line in fp:
        print(line)
第一個文件操作案例。Hello world

文本文件的讀取方法

文本文件的寫入方法

Hello world

文本文件的讀取方法

文本文件的寫入方法
with open('sample_new.txt','r') as fp:
    lines = fp.readlines()   # 操作大文件是不建議這樣使用
    print(''.join(lines))
第一個文件操作案例。Hello world
文本文件的讀取方法
文本文件的寫入方法
Hello world
文本文件的讀取方法
文本文件的寫入方法

5.移動文件指針

fp = open('sample_new.txt','r+')
fp.tell()  # 返回指針當前位置
0
fp.read(20) # 讀取20個字符
'第一個文件操作案例。Hello '
fp.seek(13)  #重新定位文件指針的位置
13
fp.write('測試')
fp.seek(0)
0
fp.read()
'測試文件操作案例。Hello world\n文本文件的讀取方法\n文本文件的寫入方法\nHello world\n文本文件的讀取方法\n文本文件的寫入方法\n'
fp.close()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM