py文件的操作

文件操作基本流程。

計算機系統分為:計算機硬件,操作系統,應用程序三部分。

我們用python或其他語言編寫的應用程序若想要把數據永久保存下來,必須要保存于硬盤中,這就涉及到應用程序要操作硬件,眾所周知,應用程序是無法直接操作硬件的,這就用到了操作系統。操作系統把復雜的硬件操作封裝成簡單的接口給用戶/應用程序使用,其中文件就是操作系統提供給應用程序來操作硬盤虛擬概念,用戶或應用程序通過操作文件,可以將自己的數據永久保存下來。

有了文件的概念,我們無需再去考慮操作硬盤的細節,只需要關注操作文件的流程:

復制代碼
#1. 打開文件,得到文件句柄并賦值給一個變量
f=open('a.txt','r',encoding='utf-8') #默認打開模式就為r#2. 通過句柄對文件進行操作
data=f.read()#3. 關閉文件
f.close()
復制代碼

關閉文件的注意事項:

打開一個文件包含兩部分資源:操作系統級打開的文件+應用程序的變量。在操作完畢一個文件時,必須把與該文件的這兩部分資源一個不落地回收,回收方法為:
1、f.close() #回收操作系統級打開的文件
2、del f #回收應用程序級的變量

其中del f一定要發生在f.close()之后,否則就會導致操作系統打開的文件還沒有關閉,白白占用資源,
而python自動的垃圾回收機制決定了我們無需考慮del f,這就要求我們,在操作完畢文件后,一定要記住f.close()雖然我這么說,但是很多同學還是會很不要臉地忘記f.close(),對于這些不長腦子的同學,我們推薦傻瓜式操作方式:使用with關鍵字來幫我們管理上下文
with open('a.txt','w') as f:passwith open('a.txt','r') as read_f,open('b.txt','w') as write_f:data=read_f.read()write_f.write(data)注意
View Code

文件編碼

f=open(...)是由操作系統打開文件,那么如果我們沒有為open指定編碼,那么打開文件的默認編碼很明顯是操作系統說了算了,操作系統會用自己的默認編碼去打開文件,在windows下是gbk,在linux下是utf-8。

#這就用到了上節課講的字符編碼的知識:若要保證不亂碼,文件以什么方式存的,就要以什么方式打開。
f=open('a.txt','r',encoding='utf-8')

文件的打開模式

文件句柄 = open(‘文件路徑’,‘模式’)

復制代碼
#1. 打開文件的模式有(默認為文本模式):
r ,只讀模式【默認模式,文件必須存在,不存在則拋出異常】
w,只寫模式【不可讀;不存在則創建;存在則清空內容】
a, 只追加寫模式【不可讀;不存在則創建;存在則只追加內容】#2. 對于非文本文件,我們只能使用b模式,"b"表示以字節的方式操作(而所有文件也都是以字節的形式存儲的,使用這種模式無需考慮文本文件的字符編碼、圖片文件的jgp格式、視頻文件的avi格式)
rb
wb
ab
注:以b方式打開時,讀取到的內容是字節類型,寫入時也需要提供字節類型,不能指定編碼#3,‘+’模式(就是增加了一個功能)
r+, 讀寫【可讀,可寫】
w+,寫讀【可寫,可讀】
a+, 寫讀【可寫,可讀】#4,以bytes類型操作的讀寫,寫讀,寫讀模式
r+b, 讀寫【可讀,可寫】
w+b,寫讀【可寫,可讀】
a+b, 寫讀【可寫,可讀】
復制代碼

?文件操作方法。

常用操作方法。

read(3):

  1. 文件打開方式為文本模式時,代表讀取3個字符

  2. 文件打開方式為b模式時,代表讀取3個字節

其余的文件內光標移動都是以字節為單位的如:seek,tell,truncate

注意:

  1. seek有三種移動方式0,1,2,其中1和2必須在b模式下進行,但無論哪種模式,都是以bytes為單位移動的

  2. truncate是截斷文件,所以文件的打開方式必須可寫,但是不能用w或w+等方式打開,因為那樣直接清空文件了,所以truncate要在r+或a或a+等模式下測試效果。

所有操作方法。

class file(object)def close(self): # real signature unknown; restored from __doc__
        關閉文件"""close() -> None or (perhaps) an integer.  Close the file.Sets data attribute .closed to True.  A closed file cannot be used forfurther I/O operations.  close() may be called more than once withouterror.  Some kinds of file objects (for example, opened by popen())may return an exit status upon closing."""def fileno(self): # real signature unknown; restored from __doc__
        文件描述符"""fileno() -> integer "file descriptor".This is needed for lower-level file interfaces, such os.read()."""return 0def flush(self): # real signature unknown; restored from __doc__
        刷新文件內部緩沖區""" flush() -> None.  Flush the internal I/O buffer. """passdef isatty(self): # real signature unknown; restored from __doc__
        判斷文件是否是同意tty設備""" isatty() -> true or false.  True if the file is connected to a tty device. """return Falsedef next(self): # real signature unknown; restored from __doc__
        獲取下一行數據,不存在,則報錯""" x.next() -> the next value, or raise StopIteration """passdef read(self, size=None): # real signature unknown; restored from __doc__
        讀取指定字節數據"""read([size]) -> read at most size bytes, returned as a string.If the size argument is negative or omitted, read until EOF is reached.Notice that when in non-blocking mode, less data than what was requestedmay be returned, even if no size parameter was given."""passdef readinto(self): # real signature unknown; restored from __doc__
        讀取到緩沖區,不要用,將被遺棄""" readinto() -> Undocumented.  Don't use this; it may go away. """passdef readline(self, size=None): # real signature unknown; restored from __doc__
        僅讀取一行數據"""readline([size]) -> next line from the file, as a string.Retain newline.  A non-negative size argument limits the maximumnumber of bytes to return (an incomplete line may be returned then).Return an empty string at EOF."""passdef readlines(self, size=None): # real signature unknown; restored from __doc__
        讀取所有數據,并根據換行保存值列表"""readlines([size]) -> list of strings, each a line from the file.Call readline() repeatedly and return a list of the lines so read.The optional size argument, if given, is an approximate bound on thetotal number of bytes in the lines returned."""return []def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
        指定文件中指針位置"""seek(offset[, whence]) -> None.  Move to new file position.Argument offset is a byte count.  Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1(move relative to current position, positive or negative), and 2 (moverelative to end of file, usually negative, although many platforms allowseeking beyond the end of a file).  If the file is opened in text mode,only offsets returned by tell() are legal.  Use of other offsets causesundefined behavior.Note that not all file objects are seekable."""passdef tell(self): # real signature unknown; restored from __doc__
        獲取當前指針位置""" tell() -> current file position, an integer (may be a long integer). """passdef truncate(self, size=None): # real signature unknown; restored from __doc__
        截斷數據,僅保留指定之前數據"""truncate([size]) -> None.  Truncate the file to at most size bytes.Size defaults to the current file position, as returned by tell()."""passdef write(self, p_str): # real signature unknown; restored from __doc__
        寫內容"""write(str) -> None.  Write string str to file.Note that due to buffering, flush() or close() may be needed beforethe file on disk reflects the data written."""passdef writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
        將一個字符串列表寫入文件"""writelines(sequence_of_strings) -> None.  Write the strings to the file.Note that newlines are not added.  The sequence can be any iterable objectproducing strings. This is equivalent to calling write() for each string."""passdef xreadlines(self): # real signature unknown; restored from __doc__
        可用于逐行讀取文件,非全部"""xreadlines() -> returns self.For backward compatibility. File objects now include the performanceoptimizations previously implemented in the xreadlines module."""pass2.x
2.x
class TextIOWrapper(_TextIOBase):"""Character and line based layer over a BufferedIOBase object, buffer.encoding gives the name of the encoding that the stream will bedecoded or encoded with. It defaults to locale.getpreferredencoding(False).errors determines the strictness of encoding and decoding (seehelp(codecs.Codec) or the documentation for codecs.register) anddefaults to "strict".newline controls how line endings are handled. It can be None, '','\n', '\r', and '\r\n'.  It works as follows:* On input, if newline is None, universal newlines mode isenabled. Lines in the input can end in '\n', '\r', or '\r\n', andthese are translated into '\n' before being returned to thecaller. If it is '', universal newline mode is enabled, but lineendings are returned to the caller untranslated. If it has any ofthe other legal values, input lines are only terminated by the givenstring, and the line ending is returned to the caller untranslated.* On output, if newline is None, any '\n' characters written aretranslated to the system default line separator, os.linesep. Ifnewline is '' or '\n', no translation takes place. If newline is anyof the other legal values, any '\n' characters written are translatedto the given string.If line_buffering is True, a call to flush is implied when a call towrite contains a newline character."""def close(self, *args, **kwargs): # real signature unknown
        關閉文件passdef fileno(self, *args, **kwargs): # real signature unknown
        文件描述符passdef flush(self, *args, **kwargs): # real signature unknown
        刷新文件內部緩沖區passdef isatty(self, *args, **kwargs): # real signature unknown
        判斷文件是否是同意tty設備passdef read(self, *args, **kwargs): # real signature unknown
        讀取指定字節數據passdef readable(self, *args, **kwargs): # real signature unknown
        是否可讀passdef readline(self, *args, **kwargs): # real signature unknown
        僅讀取一行數據passdef seek(self, *args, **kwargs): # real signature unknown
        指定文件中指針位置passdef seekable(self, *args, **kwargs): # real signature unknown
        指針是否可操作passdef tell(self, *args, **kwargs): # real signature unknown
        獲取指針位置passdef truncate(self, *args, **kwargs): # real signature unknown
        截斷數據,僅保留指定之前數據passdef writable(self, *args, **kwargs): # real signature unknown
        是否可寫passdef write(self, *args, **kwargs): # real signature unknown
        寫內容passdef __getstate__(self, *args, **kwargs): # real signature unknownpassdef __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __next__(self, *args, **kwargs): # real signature unknown""" Implement next(self). """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passbuffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
_CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
_finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default3.x
3.x

文件的修改。

文件的數據是存放于硬盤上的,因而只存在覆蓋、不存在修改這么一說,我們平時看到的修改文件,都是模擬出來的效果,具體的說有兩種實現方式:

方式一:將硬盤存放的該文件的內容全部加載到內存,在內存中是可以修改的,修改完畢后,再由內存覆蓋到硬盤(word,vim,nodpad++等編輯器)

import os  # 調用系統模塊

with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:data=read_f.read() #全部讀入內存,如果文件很大,會很卡data=data.replace('alex','SB') #在內存中完成修改
write_f.write(data) #一次性寫入新文件

os.remove('a.txt')  #刪除原文件
os.rename('.a.txt.swap','a.txt')   #將新建的文件重命名為原文件
方法一

方式二:將硬盤存放的該文件的內容一行一行地讀入內存,修改完畢就寫入新文件,最后用新文件覆蓋源文件

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') 
方法二

?

轉載于:https://www.cnblogs.com/wy3713/p/9135639.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/397771.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/397771.shtml
英文地址,請注明出處:http://en.pswp.cn/news/397771.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

CentOS系統啟動流程你懂否

一、Linux內核的組成相關概念:Linux系統的組成部分:內核根文件系統內核:進程管理、內存管理、網絡協議棧、文件系統、驅動程序。IPC(Inter-Process Communication進程間通信):就是指多個進程之間相互通信,交換信息的方法。Linux I…

怎樣用css設置圖片下的投影,css – 做這種投影的最佳方法是什么?

如果您更喜歡使用CSS來創建該類型的陰影,則可以將CSS3用作seen here!CSS/* Lifted corners */.lifted {-moz-border-radius:4px;border-radius:4px;}.lifted:before,.lifted:after {bottom:15px;left:10px;width:50%;height:20%;max-width:300px;-webkit-Box-shadow:0 15px 10p…

mysql 排版 指令_Mysql語句排版

SQL 高效排版指北統一 SQL 排版的相關用法,極大提高編寫和維護 SQL 的效率。注: column 選取的字段;table 選取的表名語句結構錯誤SELECT column1 FROM table1 ORDER BY column1正確SELECTcolumn1FROMtable1ORDER BYcolumn1解析SQL 語句在內部執行時會…

Linux命令學習手冊-tr命令 2015-07-26 20:35 9人閱讀 評論(0) 收藏...

tr [OPTION]... SET1 [SET2] [功能] 轉換或者刪除字符。 [描述] tr指令從標準輸入設備讀取數據,經過字符串轉譯后,輸出到標準輸出設備。 通過使用 tr,您可以非常容易地實現 sed 的許多最基本功能。您可以將 tr 看作為 sed 的&#xff08…

css商品,商品標簽例子——CSS3 transform 屬性

積累很重要。從此開始記錄前端生涯的點滴....div{width:150px;height:30px;background-color:#f83944;/* Rotate div */transform:rotate(-40deg);-ms-transform:rotate(-40deg); /* Internet Explorer */-moz-transform:rotate(-40deg); /* Firefox */-webkit-transform:rotat…

The literal of int xxxxx is out of range

有時候我們定義了long型的變量,當我們給該變量賦值過長的整數時,系統依然會提示長度超過范圍,解決辦法如下: long timeShow 1437565243495L; 我們需要在整形變量的后面加上“L”,便可以避免系統報錯。轉載于:https://…

debian 訪問 windows 共享_【續】windows環境redis未授權利用方式梳理

01Redis未授權產生原因1.redis綁定在0.0.0.0:6379默認端口,直接暴露在公網,無防火墻進行來源信任防護。2.沒有設置密碼認證,可以免密遠程登錄redis服務02漏洞危害1.信息泄露,攻擊者可以惡意執行flushall清空數據2.可以通過eval執行…

HTML比較常用的標簽

1.全局架構標簽&#xff1a;<html><head><title>標題</title><meta charset"utf-8"></head><body>正文部分</body></html><!--注釋部分-->2.body標簽的屬性bgcolor&#xff1a;背景色text:整個網頁的顏…

sae項目服務器,基于SAE的游戲服務器: Server on SAE for RGSS Games 部署在SAE上的簡易游戲服務器,為用 RMXP/VX/VA 開發的游戲提供網絡服務...

本項目已經關閉服務端已經關閉并且不再重啟&#xff0c;后續請訪問 RGSOS on Gitlab基于SAE的游戲服務器重寫服務端邏輯中……暫時無法正常提供服務功能數據庫封裝封裝了 SAE 上的 Memcached&#xff0c;KVDB 和 Storage 到 SAE_IO 類&#xff0c;并引申到兩個子類&#xff1a;…

1090 Highest Price in Supply Chain (25)

A supply chain is a network of retailers&#xff08;零售商&#xff09;, distributors&#xff08;經銷商&#xff09;, and suppliers&#xff08;供應商&#xff09;-- everyone involved in moving a product from supplier to customer. Starting from one root suppli…

mysql 列數據顯示轉成行數據顯示_Mysql的列修改成行并顯示數據的簡單實現

創建測試表&#xff1a;DROP TABLE IF EXISTS test;CREATE TABLE test (year int(11) DEFAULT NULL,month int(11) DEFAULT NULL,amount double DEFAULT NULL) ENGINEInnoDB DEFAULT CHARSETutf8;插入數據&#xff1a;INSERT INTO test VALUES (1991, 1, 1.1);INSERT INTO test…

Android兩種常見錯誤(ANR和FC)解決辦法

ANR(Activity Not Respone)(無響應)先介紹下Main線程&#xff08;也稱為UI線程、主線程&#xff09;功能: 1.創建UI控件2.更新UI控件狀態3.事件處理限制&#xff1a;Main線程不建議有超過5秒的事件出現條件&#xff1a;當用戶輸入事件5s內沒有得到響應&#xff0c;將彈出ANR對話…

mysql命令(command)

連接mysql命令: mysql -h 192.168.1.1 -P 3306 -uuserName -pPassword 顯示表的索引: SHOW INDDEX FROM table_name 查看mysql的超時時間&#xff1a;SHOW GLOBAL VARIABLES LIKE %timeout% 備份表結構和表數據&#xff1a;mysqldump -u用戶名 -p 庫名 表1 表2 > xxx.sql只…

微信5.0登錄提示服務器繁忙,iOS集成友盟社會化分享微信無法登錄?

iOS集成友盟社會化分享SDK-5.0點擊微信登錄的時候出現無法獲取accessToken的現象&#xff0c;其他如QQ、微博都可以正常登錄使用。另外QQ、微博和微信分享都可以正常使用。望各位早日幫我解決或者分析一下。謝謝//微信登錄之后的回調- (BOOL)application:(UIApplication *)appl…

sql獲取某列出現頻次最多的值_業務硬核SQL集錦

戳上方藍字關注我 這兩年學會了跑sql&#xff0c;當時有很多同學幫助我精進了這個技能&#xff0c;現在也寫成一個小教程&#xff0c;反饋給大家。適用對象&#xff1a;工作中能接觸到sql查詢平臺的業務同學(例如有數據查詢權限的產品與運營同學)適用場景&#xff1a;查詢hive&…

void ,NULL與0的區別聯系

void ,NULL及0的區別聯系 void的詳解: void的字面意思是“無類型”或“空類型”&#xff0c;void*則為“無針型指針”&#xff0c;那就意味著void*可以指向任何類型的數據。 眾所周知&#xff0c;如果指針p1和p2的類型相同&#xff0c;那么我們可以直接在p1和p2間互相賦值&…

python 2 days

1&#xff0c;格式化輸出&#xff0c;%s %d 2&#xff0c;復習昨日講題 編譯型&#xff1a; 將代碼一次性全部編譯成二進制&#xff0c;然后運行。 優點&#xff1a;執行效率高。 缺點&#xff1a;開發效率低&#xff0c;不能跨平臺。 C解釋型&#xff1a; 代碼…

nginx編譯安裝與配置使用

第一部分----nginx基本應用源碼編譯安裝nginx1、安裝pcre軟件包&#xff08;使nginx支持http rewrite模塊&#xff09;yum install -y pcre yum install -y pcre-devel2、安裝openssl-devel&#xff08;使nginx支持ssl&#xff09;yum install -y openssl-devel3、創建用戶ngin…

ubuntu+查看服務器文件夾權限,Ubuntu - 文件夾權限查看與修改

Ubuntu 文件的歸屬身份有四種&#xff1a;u - 擁有文件的用戶(所有者)g - 所有者所在的組群o - 其他人(不是所有者或所有者的組群)a - 每個人或全部(u, g, o)1. 查看文件/文件夾權限ls -l filename # 查看文件權限ls -ld folder # 查看文件夾權限輸出結果如&#xff1a;drwxrwx…

mysql dump 1449_跨版本mysqldump恢復報錯Errno1449

已經有一套主從mysql,新增兩個slave主庫Server version: 5.6.22-log MySQL Community Server (GPL)舊從庫Server version: 5.6.28-log MySQL Community Server (GPL)新增SLAVE 1&#xff1a; Server version: 5.6.22-log MySQL Community Server (GPL)新增SLAVE 2&#xff1a; …