用python與檔案進行互動的方法,python檔案互動

來源:互聯網
上載者:User

用python與檔案進行互動的方法,python檔案互動

本文介紹了用python與檔案進行互動的方法,分享給大家,具體如下:

一.檔案處理

1.介紹

電腦系統:電腦硬體,作業系統,應用程式

應用程式無法直接操作硬體,通過作業系統來操作檔案,進而讀/寫硬體中的檔案。

python開啟檔案過程:

#開啟f=open('a.txt','r')#通過控制代碼對檔案進行操作read_f=f.read()#關閉檔案f.close()with open('a.txt','r') as f:  #不需要關閉
f.close() #回收作業系統開啟的檔案del f #回收應用程式級的變數

2.開啟檔案的模式

a.開啟文字檔

#r,唯讀模式【預設模式,檔案必須存在,不存在則拋出異常】f=open('a.txt',encoding='utf-8')data1=f.read()print(f.readline(),end='')print(f.readlines())
#w,唯寫模式【不可讀;不存在則建立;存在則清空內容】f=open('a.txt','w',encoding='utf-8')f.write('werf')
#a,只追加寫入模式【不可讀;不存在則建立;存在則只追加內容】f=open('a.txt','a',encoding='utf-8')f.write('werf\n')

b.對於非文字檔,只能使用b模式,"b"表示以位元組的方式操作(而所有檔案也都是以位元組的形式儲存的,使用這種模式無需考慮文字檔的字元編碼、圖片檔案的jgp格式、視頻檔案的avi格式

with open('1.jpg','rb') as f_read:  data=f_read.read()  print(data)
with open('a.txt','rb') as f_read:  data=f_read.read().decode('utf-8') #解碼  print(data)
with open('a.txt','wb')as f_write:  f_write.write('adsf'.encode('utf-8'))
'''練習,利用b模式,編寫一個cp工具,要求如下:  1. 既可以拷貝文本又可以拷貝視頻,圖片等檔案  2. 使用者一旦參數錯誤,列印命令的正確使用方法,如usage: cp source_file target_file'''import sysif len(sys.argv)!=3:  print('usage:cp source_file target_file')  sys.exit()source_file,target_file=sys.argv[1],sys.argv[2]print()with open(source_file,'rb')as f_read,open(target_file,'wb')as f_write:  for line in f_read:    f_write.write(line)

3.檔案內游標的移動

#以文字模式讀檔案,n代表的是字元的個數with open('a.txt','r')as f_read:  data=f_read.read(6)  print(data)
#以b模式讀檔案,n代表的是位元組的個數with open('a.txt','rb')as f_read:  data=f_read.read(6)  print(data)
# tell:告訴當前游標的位置with open('a.txt','r',encoding='utf-8')as f_read:  data=f_read.read(4)  data1=f_read.tell()  print(data,data1)
# seek:移動游標(0:檔案開頭預設;1:檔案當前游標;2:檔案末尾)with open('a.txt', 'r', encoding='utf-8')as f_read:  data = f_read.seek(3)  data1 = f_read.read()  print(data, data1)
# 實現tail功能import timewith open('access.log', 'rb')as f_read:  f_read.seek(0,2)  while True:    line = f_read.readline()    if line:      print(line.decode('utf-8'),end='')    else:      time.sleep(1)

4.檔案的修改

import oswith open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:  for line in read_f:    line=line.replace('alex','SB')    write_f.write(line)os.remove('a.txt')os.rename('.a.txt.swap','a.txt')

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.