python操作text檔案 讀取 寫入 清空

2022-08-23 05:18:09 字數 1523 閱讀 5975

#text的儲存格式為每一行的字串儲存

#text檔案的寫入

data='尊敬的領導:\n\t您好,'#可以通過轉義字元實現換行、縮排

# with open(r'./test.txt',mode='w',encoding='utf8') as tf:

# tf.write(data)

#迭**入

list2=['尊敬的領導:\n','\t您好\n']#必須帶換行符『\n』,否則只插入一行

with open(r'./test.txt',mode='w',encoding='utf8') as tf2:

tf2.writelines(list2)

#末行追加,mode='a'表示末行追加模式,檔案必須已存在

data2='我是末行追加'

with open(r'./test.txt',mode='a',encoding='utf8') as tf3:

tf3.write(data2)

#清空檔案內容,適用於任何能用記事本正常開啟的檔案

with open(r'./test.log',mode='w',encoding='utf8') as tf2:

tf2.truncate()

#text檔案的讀取

#讀取所有內容,返回字串

with open(r'./test.txt',mode='r',encoding='utf8') as rf:

content=rf.read()

print(content)#尊敬的領導:\n\t您好\n我是末行追加

#按行讀取,以列表形式返回每行內容(上一行以『\n』結尾)

with open(r'./test.txt',mode='r',encoding='utf8') as rf2:

content2=rf2.readlines()

print(content2)#['尊敬的領導:\n', '\t您好\n', '我是末行追加']

#按元素讀取行,-1表示讀取所有行,n(n>=0)表示讀取前幾個元素,以列表形式返回元素所在的行

with open(r'./test.txt',mode='r',encoding='utf8') as rf3:

content3=rf3.readlines(7)

print(content3)#['尊敬的領導:\n', '\t您好\n']

#指定讀取首行元素,-1表示讀取整行,n(n>=0)表示讀取前幾個元素,返回字串

with open(r'./test.txt',mode='r',encoding='utf8') as rf4:

content4=rf4.readline(2)

print(content4)#'尊敬'

Python 檔案操作 讀

1.read num表示要從檔案中讀取的資料的長度 單位是位元組 如果沒有傳入num,表示讀取檔案中的全部資料。檔案物件.read num 2.readlines readlines可以按照行的方式把整個檔案中的內容進行一次性讀取,並返回的是乙個列表,其中每一行的資料為乙個元素。開啟檔案 f ope...

log檔案的讀並寫入 text檔案

今天要寫乙個功能的 讀.log檔案並去相關字段寫入.txt 在此做個筆記!public const string readfilepath c documents and settings admin 桌面access 20111207.log public const string writefi...

python 檔案操作,讀檔案,寫檔案

讀取檔案的全部內容 def get f none try f open 致橡樹.txt r encoding utf 8 print f.read except filenotfounderror print 無法開啟指定的檔案 except lookuperror print 指定了未知的編碼 e...