Python 對於檔案處理的方法
快速測試:
-
開啟互動式指令:
#python3
Python 3.4.3 (default, Jan 26 2016, 02:25:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
-
對檔案進行寫入文字的動作:
>>> text1 = "This is a test files!"
>>> fileOut = open('test1.txt','wt')
>>> fileOut.write(text1)
21
>>>quit()
#
-
驗證寫入結果:
$ cat test1.txt
This is a test files!
-
編寫讀取檔案的程式:
#vim readFiles.py
class readFiles():
def __init__(self):
self.__name = ""
def readFiles(self,name):
self.__files = open(name,'rt').read()
return self.__files
testfiles = readFiles()
print(testfiles.readFiles("test1.txt"))
-
執行程式:
#python3 readFiles.py
This is a test files!
-
修改一下檔案的程式:
#vim readFiles.py
class readFiles():
def __init__(self):
self.__name = ""
def readFiles(self,name):
self.__files = open(name,'rt')
po = self.__files.read()
self.__files.close()
return po
def readLines(self,name):
self.__lines = open(name,'rt')
lin = len(self.__lines.readlines())
self.__lines.close()
return lin
testfiles = readFiles()
print(testfiles.readFiles("test1.txt"))
print("test1.txt has ",testfiles.readLines("test1.txt")," lines")
執行程式:
#python3 readFiles.py
This is a test files!
Hello World !!
This is the 3rd lines!!
test1.txt has 3 lines