国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

用python與文件進行交互的方法

2020-01-04 15:46:55
字體:
來源:轉載
供稿:網友

本文介紹了用python/293572.html">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')

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 田林县| 郧西县| 芜湖县| 永和县| 瓮安县| 平昌县| 巴马| 尖扎县| 安龙县| 邹城市| 花垣县| 久治县| 平乡县| 哈尔滨市| 红安县| 永年县| 鹰潭市| 平谷区| 扎囊县| 改则县| 潼南县| 上杭县| 蓝山县| 明光市| 兴安县| 东山县| 邢台县| 高青县| 黑水县| 水富县| 安国市| 婺源县| 辰溪县| 新巴尔虎左旗| 南安市| 班玛县| 莫力| 垦利县| 蓬安县| 宾阳县| 石嘴山市|