python文件管理_超值的Python文件操作与管理!
📚文件操作與管理目錄
文件操作
打開文件
file參數(shù)
mode參數(shù)
buffering參數(shù)
encoding參數(shù)和errors參數(shù)
newline參數(shù)
closfd和opener參數(shù)
關(guān)閉文件
文本文件讀寫
os模塊
os模塊函數(shù)文檔
大家可以根據(jù)上面的目錄,在博客右邊目錄中查找
打開文件
文件對象可以通過open()函數(shù)獲得。open()函數(shù)是Python內(nèi)置函數(shù),它屏蔽了創(chuàng)建文件對象的細節(jié),使得創(chuàng)建文件對象變得簡單。open函數(shù)語法如下:
open(file, node='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
open有8個參數(shù),其中file和mode最常用,其他很少使用
file參數(shù)
file參數(shù)是要打開的文件,可以是字符串或整數(shù)。如果file是字符串表示文件名,文件名可以是相對當前目錄的路徑,也可以是絕對路徑里如果file是整數(shù)表示文件描述符,文件描述符指向一個已經(jīng)打開的文件。
mode參數(shù)
設(shè)置文件打開模式,二進制文件要設(shè)置rb、wb、xb、ab,如果是文本文件需要設(shè)置rt、wt、xt、at,由于t是默認模式,所以可以省略為r、w、x、a。
文件打開方式
字符串
說明
r
只讀模式打開文件(默認)
w
寫入模式打開文件,會覆蓋已經(jīng)存在的文件
x
獨占創(chuàng)建模式,文件不存在時創(chuàng)建并以寫入模式打開,如果文件已存在則拋出異常
a
追加模式,如果文件存在則寫入內(nèi)容追加到文件末尾
b
二進制模式
t
文本模式(默認)
+
更新模式
+必須與r、w、x或a組合使用來設(shè)置文件為讀寫模式
buffering參數(shù)
buffering函數(shù)是設(shè)置緩沖區(qū),默認值為-1,目前不用知道。
encoding和errors參數(shù)
encoding參數(shù)是指定文件打開時的編碼設(shè)置,errors參數(shù)是指定編碼發(fā)生錯誤時的策略
newline參數(shù)
設(shè)置換行格式
closfd和opener參數(shù)
賊file參數(shù)為文件描述符時使用,不用管。
實例代碼:
# -*-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
提示:文件路徑中的\字符會轉(zhuǎn)義,所以加上r可以定為原字符串,防止轉(zhuǎn)義,或者改成/或\\都可以防止轉(zhuǎn)義
例:原路徑:‘C:\Users\33924\Documents\test.txt',防止轉(zhuǎn)義的方式有如下三種
r'C:\Users\33924\Documents\test.txt'
‘C:\\Users\\33924\\Documents\\test.txt’
‘C:/Users/33924/Documents/test.txt’
關(guān)閉文件
一定要記住這里,關(guān)閉文件很重要,當使用open()函數(shù)打開文件后,若不再使用文件應(yīng)該調(diào)用文件對象的close()方法關(guān)閉文件,文件的操作往往會拋出異常,為了保證文件操作無論正常結(jié)束還是異常結(jié)束都能夠關(guān)閉文件,調(diào)用close()方法應(yīng)該放在異常處理的finally代碼塊中。
實例代碼:
# -*- coding: UTF-8 -*-
#!/usr/bin/python3
# 使用finally關(guān)閉文件
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
文件內(nèi)容(test.txt)
hello world
C++同樣,打開之后一定要關(guān)閉,否則很容易混淆。
文本文件讀寫
文本文件讀寫的單位是字符,而且字符是有編碼的,比如中文的編碼就要用Unicode或GBK等
主要方法有以下幾種
read(size=-1):從文件中讀取字符串,size限制最多讀取的字符數(shù),size=-1時沒有限制
readline(size=-1):讀取到換行符或文件尾并返回單行字符串,size是限制,等于-1沒有限制
readlines(hint=-1):讀取一個字符串列表,每一行是列表的一個單元,hint是限制幾行,等于-1沒有限制
write(s):寫入一個字符串s,并返回寫入的字符數(shù)
writelines(lines):向文件寫入一個列表,不添加行分隔符
flush():刷新寫緩沖區(qū)
實例代碼:
# -*- 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('文件復(fù)制成功')
輸出:
['hello world\n', 'hello world\n', 'hello world']
lines的類型是:
文件復(fù)制成功
test.txt文件:
hello world
hello world
hello world
copy.txt文件:
hello world
hello world
hello world
打開文件時需要指定文件編碼,比如UTF-8
os模塊
Python對文件的操作是通過文件對象實現(xiàn)的,文件對象屬于Python的io模塊。如果通過Python程序管理文件或目錄,如刪除文件、修改文件名、創(chuàng)建目錄、刪除目錄和遍歷目錄等,可以通過Python的os模塊實現(xiàn)。
注:目錄就是文件夾
常用函數(shù):
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):經(jīng)典的shell指令,創(chuàng)建文件夾,在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模塊函數(shù)文檔
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.
如有問題請評論
總結(jié)
以上是生活随笔為你收集整理的python文件管理_超值的Python文件操作与管理!的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql any运算符_MySQL 运
- 下一篇: python读取文件夹下所有图像 预处理