python中文件操作


1.創建和打開文件

(1)打開模式:

r:以只讀模式打開;r+:以讀寫模式打開;w:以只寫模式打開(重寫文件,不存在則創建)

w+:以讀/寫模式打開;a:只寫模式(只允許在末尾追加);a+以讀/寫模式打開

>>> fo=open('test.txt')
>>> fo
<open file 'test.txt', mode 'r' at 0x0000000003AC3AE0>
>>> fo.read()
'123'

>>> fo=open('test.txt','w')
>>> fo
<open file 'C:/Users/kite/Desktop/test.txt', mode 'w' at 0x0000000003AC3AE0>

>>> fo.close()

(2)寫文件(write()寫入字符串、writelines()寫入字符串序列)

>>> fo=open('test.txt','w')
>>> fo.write('english id ')

 

>>> fo=open('test.txt','w+')

>>> fo.writelines(['I\n','learn\n','python\n'])

>>> fo.read()
'I\nlearn\npython\n'

(3)保存和關閉文件(close()和flush())

a.結合異常機制確保文件關閉

>>> try:
... f=open('test.txt','w+'))
... f.write('test')
... except BaseException as e:
... print(e)
... finally:
... f.close()

b.with語句自動管理上下文資源

>>> with open('test.txt','w+') as f:
... f.write('testtest')

(4)讀文件

read(),讀取並返回整個文件;

>>> with open('test.txt','r') as f:
... s=f.read()
... print(s)
...
testt\nest\ntest\ntes\nttesttest\nttttt
stesttesttestsstesttesttests\n
stesttesttestsstesttesttests\n
stesttesttests

readline(),只返回一行結果;

>>> with open('test.txt','r') as f:
... line=f.readline()
... print(line)
...
testt\nest\ntest\ntes\nttesttest\nttttt

readlines(),一次讀取所有,返回一個列表

>>> with open('test.txt','r') as f:
... content=f.readlines()
... print(content)
...
['testt\\nest\\ntest\\ntes\\nttesttest\\nttttt\n', 'stesttesttestsstesttesttests\\n\n', 'stesttesttestsstesttesttests\\n\n', 'stesttesttests']

2.文件讀寫位置

(1)tell(),返回文件當前位置

>>> fo=open('test.txt')
>>> fo.tell()
0L
>>> print(fo.read(5))
testt
>>> fo.tell()
5L

(2)seek(),移動文件讀取指針到指定位置,實現文件隨機讀寫

>>> fo.seek(5,0)
>>> fo.tell()
5L
>>> print(fo.read())
\nest\ntest\ntes\nttesttest\nttttt
stesttesttests

3.文件迭代器

每讀取一行加載到內存中

>>> fo=open('test.txt')
>>> for line in fo:
... print(line)
...
testt\nest\ntest\ntes\nttesttest\nttttt

stestt

 

>>> fo=open('test.txt')
>>> for line in fo.readlines():
... print(line)
...
testt\nest\ntest\ntes\nttesttest\nttttt

stestt

4.copy模塊(在定義類時,通過定義__copy__和__deepcopy__方法,可改變copy默認行為)

(1)淺拷貝copy.copy(只復制對象本身,未復制該對象所引用的對象)

>>> import copy
>>> a=[1,2,3,['a','b','c']]
>>> b=a
>>> c=copy.copy(a)
>>> c
[1, 2, 3, ['a', 'b', 'c'],'e']

>>> a
[1, 2, 3, ['a', 'b', 'c'],'e']

>>> c[3][0]='g'
>>> c
[1, 2, 3, ['g', 'b', 'c'], 'e']
>>> a
[1, 2, 3, ['g', 'b', 'c'], 'e']

(2)深拷貝copy.deepcopy(復制對象及該對象所引用的對象)

>>> d=copy.deepcopy(b)
>>> b
[1, 2, 3, ['a', 'b', 'c'], 'e']
>>> d
[1, 2, 3, ['a', 'b', 'c'], 'e']
>>> d[3][1]='f'
>>> d
[1, 2, 3, ['a', 'f', 'c'], 'e']
>>> b
[1, 2, 3, ['a', 'b', 'c'], 'e']

5.os模塊

(1)創建目錄(mkdir()/makedirs())

>>> import os
>>> os.mkdir('test')
>>> os.mkdirs('a/b/c')

(2)刪除目錄(rmdir()\removedirs())

>>> os.rmdir('test')
>>> os.removedirs('a/b/c')

(3)創建/刪除文件(mknod()/remove())

>>> os.mknod('test.txt')

>>> os.remove('test.txt')

(4)獲取當前路徑(getcwd())

>>> os.getcwd()
'C:\\Python'

(5)切換目錄(chdir())

 >>>os.chdir('/')

(6)列出目錄下的所有目錄和文件(listdir())

>>> os.listdir('.')
['3.py', 'a.py', 'chromedriver.exe', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'tcl', 'test1', 'Tools']

(7)文件重命名(rename(old,new)

>>> os.rename('test.txt','a.txt')

(8)獲取文件/文件夾名

>>> os.path.basename('c:\test.txt')

'test.txt'

(9)獲取文件/文件夾路徑

>>> os.path.dirname('c:\test.txt')

'C:\\'

(10)遍歷樹生成文件名(os.walk(top[,topdown=True[,onerror=None[,followlinks=False]]]))

top - 以目錄為根的每個目錄產生3元組,即(dirpath,dirnames,filenames)。dirpath為目錄的路徑,為一個字符串。

dirnames列出了目錄路徑下面所有存在的目錄的名稱。

filenames列出了目錄路徑下面所有文件的名稱。

topdown - 如果可選參數topdown為True或未指定,則從上到下掃描目錄。如果topdown設置為False,則會自下而上掃描目錄,不懂的話可以看下圖的結果就明白了

onerror - 這可能會顯示錯誤以繼續行走,或者引發異常以中止行走。

followlinks - 如果設置為true,則訪問符號鏈接指向的目錄。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM