超值的Python文件操作與管理!

倉庫:https://github.com/Github-Programer/Coding-Notes/
這個筆記的位置
這麼長的文章怎麼能不點贊呢?

📚文件操作與管理目錄

  • 文件操作
  • 打開文件
    • file參數
      • mode參數
      • buffering參數
      • encoding參數和errors參數
      • newline參數
      • closfd和opener參數
    • 關閉文件
    • 文本文件讀寫
  • os模塊
  • os模塊函數文檔

大家可以根據上面的目錄,在博客右邊目錄中查找

打開文件

 文件對象可以通過open()函數獲得。open()函數是Python內置函數,它屏蔽了創建文件對象的細節,使得創建文件對象變得簡單。open函數語法如下:

	open(file, node='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

open有8個參數,其中filemode最常用,其他很少使用

file參數

file參數是要打開的文件,可以是字符串或整數。如果file是字符串表示文件名,文件名可以是相對當前目錄的路徑,也可以是絕對路徑裏如果file是整數表示文件描述符,文件描述符指向一個已經打開的文件。

mode參數

設置文件打開模式,二進制文件要設置rb、wb、xb、ab,如果是文本文件需要設置rt、wt、xt、at,由於t是默認模式,所以可以省略爲r、w、x、a。

文件打開方式
字符串 說明
r 只讀模式打開文件(默認)
w 寫入模式打開文件,會覆蓋已經存在的文件
x 獨佔創建模式,文件不存在時創建並以寫入模式打開,如果文件已存在則拋出異常
a 追加模式,如果文件存在則寫入內容追加到文件末尾
b 二進制模式
t 文本模式(默認)
+ 更新模式

+必須與r、w、x或a組合使用來設置文件爲讀寫模式

buffering參數

buffering函數是設置緩衝區,默認值爲-1,目前不用知道。

encoding和errors參數

encoding參數是指定文件打開時的編碼設置,errors參數是指定編碼發生錯誤時的策略

newline參數

設置換行格式

closfd和opener參數

賊file參數爲文件描述符時使用,不用管。


實例代碼:

# -*-coding: UTF-8 -*-
#!/usr/bin/python3

f = open('test.txt', 'w+')
f.write('World')

f = open('test.txt', 'r+')
f.write('Hello')

f = open('test.txt', 'a')
f.write(' ')

fname = r'E:\王一涵programThomas\王一涵PythonThomas\Python-Learned\第十五章-文件操作與管理\文件操作代碼01\test.txt'
f = open(fname, 'a+')
f.write('World');

最後文件中的文檔是:

Hello World

提示:文件路徑中的\字符會轉義,所以加上r可以定爲原字符串,防止轉義,或者改成/\\都可以防止轉義
例:原路徑:‘C:\Users\33924\Documents\test.txt',防止轉義的方式有如下三種

  • r'C:\Users\33924\Documents\test.txt'
  • ‘C:\\Users\\33924\\Documents\\test.txt’
  • ‘C:/Users/33924/Documents/test.txt’

關閉文件

一定要記住這裏,關閉文件很重要,當使用open()函數打開文件後,若不再使用文件應該調用文件對象的close()方法關閉文件,文件的操作往往會拋出異常,爲了保證文件操作無論正常結束還是異常結束都能夠關閉文件,調用close()方法應該放在異常處理的finally代碼塊中。

實例代碼:

# -*- coding: UTF-8 -*-
#!/usr/bin/python3

# 使用finally關閉文件
f_name = 'test.txt'
try:
    f = open(f_name)
except OSError as e:
    print('打開文件失敗')
else:
    print('打開文件成功')
    try:
        content = f.read()
        print(content)
    except OSError as e:
        print('處理OSError異常')
    finally:
        f.close()

# 使用with as自動資源管理
with open(f_name, 'r') as f:
    content = f.read()
    print(content)

輸出:

打開文件成功
hello world
hello world

文件內容(test.txt)

hello world

C++同樣,打開之後一定要關閉,否則很容易混淆。

文本文件讀寫

文本文件讀寫的單位是字符,而且字符是有編碼的,比如中文的編碼就要用Unicode或GBK等

主要方法有以下幾種

  • read(size=-1):從文件中讀取字符串,size限制最多讀取的字符數,size=-1時沒有限制
  • readline(size=-1):讀取到換行符或文件尾並返回單行字符串,size是限制,等於-1沒有限制
  • readlines(hint=-1):讀取一個字符串列表,每一行是列表的一個單元,hint是限制幾行,等於-1沒有限制
  • write(s):寫入一個字符串s,並返回寫入的字符數
  • writelines(lines):向文件寫入一個列表,不添加行分隔符
  • flush():刷新寫緩衝區

實例代碼:

# -*- coding: UTF-8 -*-
#!/usr/bin/python3

f_name = 'test.txt'

with open(f_name, 'r', encoding='UTF-8') as f:
    lines = f.readlines()
    print(lines)
    print('lines的類型是:', type(lines))
    copy_f_name = 'copy.txt'
    with open(copy_f_name, 'w', encoding='utf-8') as copy_f:
        copy_f.writelines(lines)
        print('文件複製成功')

輸出:

['hello world\n', 'hello world\n', 'hello world']
lines的類型是: <class 'list'>
文件複製成功

test.txt文件:

hello world
hello world
hello world

copy.txt文件:

hello world
hello world
hello world

打開文件時需要指定文件編碼,比如UTF-8

os模塊

Python對文件的操作是通過文件對象實現的,文件對象屬於Python的io模塊。如果通過Python程序管理文件或目錄,如刪除文件、修改文件名、創建目錄、刪除目錄和遍歷目錄等,可以通過Python的os模塊實現。
注:目錄就是文件夾

常用函數:

  • os.rename(src, dst):修改文件名,src是源文件,dst是目標文件,它們都可以是相對當前路徑或絕對路徑表示的文件
  • os.remove(path):刪除path所指的文件,如果path是目錄,拋出異常OSError
# -*-coding: UTF-8 -*-
#!/usr/bin/python3
import os

os.rename(r"E:\王一涵programThomas\Coding-Notes\Python-Notes\第十五章-文件操作與管理\OS_Module\1.rename_remove\test.txt",
          r"E:\王一涵programThomas\Coding-Notes\Python-Notes\第十五章-文件操作與管理\OS_Module\1.rename_remove\last.txt")
'''
rename文檔:
---
rename(src: _PathType, dst: _PathType, *, src_dir_fd: Optional[int]=..., dst_dir_fd: Optional[int]=...) -> None
param src: _PathType

Rename a file or directory.
If either src_dir_fd or dst_dir_fd is not None, it should be a file
descriptor open to a directory, and the respective path string (src or dst)
should be relative; the path will then be relative to that directory.
src_dir_fd and dst_dir_fd, may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
'''

os.remove(r'E:\王一涵programThomas\Coding-Notes\Python-Notes\第十五章-文件操作與管理\OS_Module\1.rename_remove\removeTEST.TXT')
'''
remove文檔:
---
remove(path: _PathType, *, dir_fd: Optional[int]=...) -> None
param path: _PathType

Remove a file (same as unlink()).
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
'''
  • os.mkdir(path):經典的shell指令,創建文件夾,在path目錄中,如果目錄已存在,就會拋出異常FileExistsError
  • os.rmdir(path):刪除path路徑的目錄,如果目錄非空,拋出異常OSError
# -*- coding: UTF-8 -*-
#!/usr/bin/python3
import os

os.mkdir(
    r"E:\王一涵programThomas\Coding-Notes\Python-Notes\第十五章-文件操作與管理\OS_Module\2.mkdir_rmdir\MKDIR"
)
'''
mkdir:
---
mkdir(path: _PathType, mode: int=..., *, dir_fd: Optional[int]=...) -> None
param path: _PathType
Create a directory.
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
The mode argument is ignored on Windows.
'''

os.rmdir(
    r"E:\王一涵programThomas\Coding-Notes\Python-Notes\第十五章-文件操作與管理\OS_Module\2.mkdir_rmdir\MKDIR"
)
'''
rmdir:
---
rmdir(path: _PathType, *, dir_fd: Optional[int]=...) -> None
param path: _PathType
Remove a directory.
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
'''
  • os.walk(top):遍歷top所指的目錄樹,自頂向下遍歷目錄樹,返回值是一個三元組(目錄路徑,目錄名列表,文件名列表)
# -*- coding: UTF-8 -*-
#!/usr/bin/python3
import os
f = open(r"E:\王一涵programThomas\Coding-Notes\Python-Notes\第十五章-文件操作與管理\OS_Module\3.walk\out\outPutOfWalk.log", 'w+', encoding='UTF-8')
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        f.write(os.path.join(root, name))
    for name in dirs:
        f.write(os.path.join(root, name))

實例代碼全在文件夾中(OS_Module…**.py)
Github代碼地址:https://github.com/Github-Programer/Coding-Notes/tree/master/Python-Notes/第十五章-文件操作與管理

os模塊函數文檔

  • rename文檔:
    rename(src: _PathType, dst: _PathType, *, src_dir_fd: Optional[int]=…, dst_dir_fd: Optional[int]=…) -> None
    param src: _PathType
    Rename a file or directory.
    If either src_dir_fd or dst_dir_fd is not None, it should be a file
    descriptor open to a directory, and the respective path string (src or dst)
    should be relative; the path will then be relative to that directory.
    src_dir_fd and dst_dir_fd, may not be implemented on your platform.
    If they are unavailable, using them will raise a NotImplementedError.
  • remove文檔:
    remove(path: _PathType, *, dir_fd: Optional[int]=…) -> None
    param path: _PathType
    Remove a file (same as unlink()).
    If dir_fd is not None, it should be a file descriptor open to a directory,
    and path should be relative; path will then be relative to that directory.
    dir_fd may not be implemented on your platform.
    If it is unavailable, using it will raise a NotImplementedError.
  • mkdir文檔
    mkdir(path: _PathType, mode: int=…, *, dir_fd: Optional[int]=…) -> None
    param path: _PathType
    Create a directory.
    If dir_fd is not None, it should be a file descriptor open to a directory,
    and path should be relative; path will then be relative to that directory.
    dir_fd may not be implemented on your platform.
    If it is unavailable, using it will raise a NotImplementedError.
    The mode argument is ignored on Windows.
  • rmdir文檔:
    rmdir(path: _PathType, *, dir_fd: Optional[int]=…) -> None
    param path: _PathType
    Remove a directory.
    If dir_fd is not None, it should be a file descriptor open to a directory,
    and path should be relative; path will then be relative to that directory.
    dir_fd may not be implemented on your platform.
    If it is unavailable, using it will raise a NotImplementedError.

參考書目:《Python從小白到大牛》——關東昇著
參考文檔:
1、https://www.runoob.com/python/os-walk.html
2、https://www.runoob.com/python/os-listdir.html
3、https://blog.csdn.net/liangyuannao/article/details/8724686
聯繫我:[email protected]🍻

如有問題請評論

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章