【289】◀▶ Python I/O 读写文本文件
參考:Python 文件 I/O
參考:Python OS 文件/目錄方法
目錄:
| 01 | ? | open 函數 | 用于打開一個文件,創建一個 file 對象,相關的方法才可以調用它進行讀寫。 |
| 02 | ? | File 對象 | file 對象使用 open 函數來創建。 |
| 03 | ? | rename 方法 | 用于命名文件或目錄。 |
| 04 | ? | remove 方法 | 用于刪除指定路徑的文件。 |
| 05 | ? | mkdir 方法 | 用于以數字權限模式創建目錄。 |
| ? | ? | makedirs 方法 | 用于多級創建目錄。 |
| 06 | ? | chdir 方法 | 用于改變當前工作目錄到指定的路徑。 |
| 07 | ? | getcwd 方法 | 用于返回當前工作目錄。 |
| 08 | ? | rmdir 方法 | 用于刪除指定路徑的目錄。 |
| 09 | ? | listdir 方法 | 用于返回指定的文件夾包含的文件或文件夾的名字的列表。 |
| 10 | ? | input 方法 | 接受一個標準輸入數據。 |
| 11 | ? | raw_input 方法 | 將所有輸入作為字符串看待,返回字符串類型。 |
| -------- | ? | ?------------------- | ?----------------------------------------------------------------------------------------------------- |
文本文件讀寫舉例:
# 實現功能:從數據中每隔4行選取一個 def a():fo = open("D:\\tmp\\a.txt", "r+")fo_w = open("D:\\tmp\\a1.txt", "w+")lines_new = fo.readlines()i = 0for l in lines_new:if i%4==0:fo_w.writelines(l[0:-1])i+=1fo.close()fo_w.close()# 實現功能:為每一個行文件添加后綴 def c():fo = open("D:\\tmp\\a.txt", "r+")fo_w = open("D:\\tmp\\a2.txt", "w+")lines_new = fo.readlines()for l in lines_new:fo_w.writelines(l+".zip\n")fo.close()fo_w.close()?
?
詳細說明:
| 序號 | 類名稱 | ? | 功能說明 | ? | 語法 & 舉例 |
| 01 | open 函數 | ? | ====<<<< Description >>>>==== 用于打開一個文件,創建一個??file? 對象,相關的方法才可以調用它進行讀寫。 ====<<<< Syntax >>>>==== open (name[, mode[, buffering]]) ====<<<< Parameters >>>>==== ?? name:一個包含了你要訪問的文件名稱的字符串值。 ====<<<< mode >>>>==== ?? r:以只讀方式打開文件。文件的指針將會放在文件的開頭。這是默認模式。文件不存在報錯。 ====<<<< References >>>>==== 參考:python文件打開方式詳解——a、a+、r+、w+區別 | ? | # 獲取柵格數據
arcpy.env.workspace=r"D:\01-Working\2017\20171204-IDL_Average\temp\TSM"
rs = arcpy.ListRasters()# 遍歷柵格數據獲取統計信息
# 首先需要建立柵格文件
# 將數據結果保留兩位小數
# 輸出到txt文檔中fo = open("D:\\01-Working\\2017\\2017_Average\\temp\\tsm_stats.txt", "w+")
for r in rs:ro = arcpy.Raster(r)fo.writelines(ro.name + "\n")fo.writelines("MAX: " + str(round(ro.maximum, 2)) + "\n")fo.writelines("MIN: " + str(round(ro.minimum, 2)) + "\n")fo.writelines("MEAN: " + str(round(ro.mean, 2)) + "\n\n")fo.close()
讀入文件示例: >>> import os >>> fo = open("D:\\03-Study\\Python\\test\\test.txt", "r+") >>># 讀取全部為一個字符串(read) >>> lines = fo.read() >>> lines 'Line 1: aaaaaa\nLine 2: bbbbbb\nLine 3: cccccc\nLine >>> print lines Line 1: aaaaaa Line 2: bbbbbb Line 3: cccccc >>> fo.tell() 110L >>># 指針返回初始位置 >>> fo.seek(0) >>> fo.tell() 0L >>># 讀取數據的一行(readline) >>> lines_new = fo.readline() >>> lines_new 'Line 1: aaaaaa\n' >>># 讀取剩下的數據為一個列表(readlines) >>> lines_new2 = fo.readlines() >>> lines_new2 ['Line 2: bbbbbb\n', 'Line 3: cccccc\n'] >>> fo.close()寫入文件示例: >>> fo = open("D:\\03-Study\\Python\\test\\test.txt", "w+") >>> a = "Alex Lee" >>> b = ["a", "b", "c"] >>> fo.write(a) #寫入全部(write) >>> fo.write("\n") #換行符 >>> fo.writelines(b) #寫入列表,無換行符(writelines) >>> for i in range(0, len(b)): ... b[i] = b[i] + "\n" ... >>> print b ['a\n', 'b\n', 'c\n'] >>> fo.write("\n") #換行符 >>> fo.writelines(b) #寫入列表,有換行符 >>> fo.close() >>> fo = open("D:\\03-Study\\Python\\test\\test.txt", "r+") >>> print fo.read() Alex Lee abc a b c? |
| 02 | File 對象 | ? | ====<<<< Description >>>>==== file 對象使用 open 函數來創建。 ====<<<< Properties >>>>==== ??? file.name:返回文件的名稱。 ====<<<< Methods >>>>==== ??? file.writelines (sequence):向文件寫入一個序列字符串列表,如果需要換行則要自己加入每行的換行符。 ====<<<< References >>>>==== 參考:python中readline判斷文件讀取結束的方法 | ? | |
| 03 | rename 方法 | ? | ?====<<<< Description >>>>==== 用于命名文件或目錄,從 src 到 dst,如果dst是一個存在的目錄, 將拋出OSError。(相當于移動文件) ====<<<< Syntax >>>>==== os.rename (src, dst) ====<<<< Parameters >>>>==== ?? src:要修改的目錄名。 | ? | >>> import os >>> os.rename(r"D:\test.txt", r"D:\test1.txt") >>> os.rename(r"D:\test1.txt", r"D:\test2.txt") |
| 04 | remove 方法 | ? | ?====<<<< Description >>>>==== 用于刪除指定路徑的文件。如果指定的路徑是一個目錄,將拋出OSError。 ====<<<< Syntax >>>>==== os.remove (path) ====<<<< Parameters >>>>==== ?? path:要移除的文件路徑。 參考:python 刪除文件、目錄(shutil.rmtree()) | ? | # 實現刪除文件夾內的HDF文件 import os rootdir = r"D:\tmp\tmp" for file in os.listdir(rootdir):if file.find("hdf") > 0:os.remove(os.path.join(rootdir, file)) |
| ?05 | mkdir 方法 | ? | ====<<<< Description >>>>==== 用于以數字權限模式創建目錄。默認的模式為 0777 (八進制)。 ====<<<< Syntax >>>>==== os.mkdir (path[, mode]) ====<<<< Parameters >>>>==== ?? path:要創建的目錄。 | ? | >>> import os >>> os.mkdir(r"D:\folder") |
| ? | makedirs 方法 | ? | ====<<<< Description >>>>==== os.makedirs() 方法用于遞歸創建目錄。像 mkdir(), 但創建的所有intermediate-level文件夾需要包含子目錄。 ? ====<<<< Syntax >>>>==== ? os.makedirs (path[, mode]) ? ====<<<< Parameters >>>>==== ? ?? path:要創建的目錄。 ? | ? | ? |
| ?06 | chdir 方法 | ? | ====<<<< Description >>>>==== 用于改變當前工作目錄到指定的路徑。(工作空間修改) ====<<<< Syntax >>>>==== os.chdir (path) ====<<<< Parameters >>>>==== ?? path:要切換到的新路徑。 | ? | >>> import os >>> print os.getcwd() D:\01-Working\2018\20180115-濃煙專題圖 >>> os.chdir(r"D:\03-Study\Python\test") >>> os.rmdir("folder") ? |
| 07 | getcwd 方法 | ? | ====<<<< Description >>>>==== 用于返回當前工作目錄。(import sys) ====<<<< Syntax >>>>==== os.getcwd () | ? | |
| 08 | rmdir 方法 | ? | ====<<<< Description >>>>==== 用于刪除指定路徑的目錄。僅當這文件夾是空的才可以, 否則, 拋出OSError。 ====<<<< Syntax >>>>==== os.rmdir (path) ====<<<< Parameters >>>>==== ?? path:要刪除的目錄路徑。 | ? | |
| ?09 | listdir 方法 | ? | ====<<<< Description >>>>==== 用于返回指定的文件夾包含的文件或文件夾的名字的列表。這個列表以字母順序。 它不包括 '.' 和'..' 即使它在文件夾中。 ====<<<< Syntax >>>>==== os.listdir (path) ====<<<< Parameters >>>>==== ?? path:需要列出的目錄路徑。 | ? | >>> import os >>> print os.listdir(r"D:\test") ['11.txt', 'cnblog1.txt', 'frame.ui'] |
| 10 | input 方法 | ? | ====<<<< Description >>>>==== Python3.x 中 input() 函數接受一個標準輸入數據,返回為 string 類型。 注意:input() 和 raw_input() 這兩個函數均能接收 字符串 ,但 raw_input() 直接讀取控制臺的輸入(任何類型的輸入它都可以接收)。而對于 input() ,它希望能夠讀取一個合法的 python 表達式,即你輸入字符串的時候必須使用引號將它括起來,否則它會引發一個 SyntaxError 。 ====<<<< Syntax >>>>=== input ([prompt]) ====<<<< Parameters >>>>==== ?? prompt:可選,字符串,可作為一個提示語。 | ? | >>> a = input("input:") input:123 >>> type(a) <type 'int'> >>> a 123 >>> a = input("input:") input:"alex" >>> a 'alex' >>> a = input("input:") input:alexTraceback (most recent call last):File "<pyshell#23>", line 1, in <module>a = input("input:")File "<string>", line 1, in <module> NameError: name 'alex' is not defined |
| 11 | raw_input 方法 | ? | ====<<<< Description >>>>==== 用來獲取控制臺的輸入。 ? ====<<<< Syntax >>>>==== ? raw_input ([prompt]) ? ====<<<< Parameters >>>>==== ? ?? prompt:可選,字符串,可作為一個提示語。 ? | ? | >>> a = raw_input("input:") input:123 >>> type(a) <type 'str'> >>> a '123' >>> a = raw_input("input:") input:alex >>> a 'alex' |
| ------ | ------------------------------ | ? | ? | ? | ? |
總結
以上是生活随笔為你收集整理的【289】◀▶ Python I/O 读写文本文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: No enclosing instanc
- 下一篇: 十年磨一剑是危险的