文本文件
os.path.exists('path/file.txt')
>>>os.path.exists("C://ArcMentalTest//config.txt")
True
f=open(path, mode)
data=f.read()
try:
f = open('/path/to/file', 'r') # 打开文件
data = f.read() # 读取文件内容
finally:
if f:
f.close() # 确保文件被关闭
with open(path, mode)
with open('/path/to/file', 'r') as f: #会自动关闭文件
data = f.read()
f.read(1024)
适用于文件较大的情况,如10G不想一次性读完
with open('path/to/file', 'r') as f:
while True:
piece = f.read(1024) # 每次读取 1024 个字节(即 1 KB)的内容
if not piece:
break
print piece
yield data
def read_in_chunks(file_object, chunk_size=1024):
"""
Lazy function (generator) to read a file piece by piece.
Default chunk size: 1k.
"""
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data #可多次返回数据
with open('path/to/file', 'r') as f:
for piece in read_in_chunks(f):
print piece
f.readline()
with open('data.txt', 'r') as f:
while True:
line = f.readline() # 逐行读取
if not line:
break
print line, # 这里加了 ',' 是为了避免 print 自动换行
f.readlines()
file.txt
-------------------------
This a test .
a file named file.txt
txt is the expend name...
-------------------------
with open('./file.txt', 'r') as f:
line = f.readline()
print(line)
-------------------------
This a test .
file.txt
-------------------------
10 1 9 9
6 3 2 8
20 10 3 23
1 4 1 10
10 8 6 3
10 2 1 6
-------------------------
with open('data.txt', 'r') as f:
lines = f.readlines() #按行读生成字符串列表
line_num = len(lines)
print lines
print line_num
------------------------
['10 1 9 9
', '6 3 2 8
', '20 10 3 23
', '1 4 1 10
', '10 8 6 3
', '10 2 1 6']
6
file.txt
-------------------------
This a test .
a file named file.txt
txt is the expend name...
-------------------------
with open('./file.txt', 'r') as f:
lines = f.readlines()
print(lines)
['This a test .
', 'a file named file.txt
', 'txt is the expend name...']
for line in f:...迭代器
with open('data.txt', 'r') as f:
for line in f:
print line,
-------------------------------
10 1 9 9
6 3 2 8
20 10 3 23
1 4 1 10
10 8 6 3
10 2 1 6
with open(file_path, 'r') as f:
lines = list(f)
print lines
------------------------------
['10 1 9 9
', '6 3 2 8
', '20 10 3 23
', '1 4 1 10
', '10 8 6 3
', '10 2 1 6']
f.write('message
')
with open('/Users/ethan/data2.txt', 'w') as f:
f.write('one
') #覆盖写,文件不存在则创建
f.write('two')
with open('/Users/ethan/data2.txt', 'a') as f: #追加写
f.write('three
')
f.write('four')
二进制文件
with open(path, 'rb') as f:...
f.read()
with open('./image/plain.png', 'rb') as f:
bs = f.read() #生成字节字符串
print(bs)
#结果
b'x89PNG
x1a
x00x00x00
IHDRx00x00x00xcex00x00x00xc8x08x06x00x00x00xa0Fxdexd9x00x00 xb6IDATxx9cxedxddAkx1bxcdx1dxc7qxbdx04xbfx82xd5x84x1eJz(x82\J!`zxf1xd59...x00x00x00x00x00x00x00x00x00x00x00x000xbbxfex0fxebx04xd6xd6xd5]xb9xe3x00x00x00x00IENDxaeB`x82'
data=base64.b64encode(byte_data)
import base64
with open('./image/plain.png', 'rb') as f:
bs = f.read()
data_64 = base64.b64encode(bs) #对字节字符串进行base64编码
print(data_64)
#结果
b'iVBORw0KGgoAAAANSUhEUgAAAM4AAADICAYAAACgRt7ZAAAJtklEQVR4nO3dQWsbzR3Hcb0Ev4LVhB5KeiiCXEohYHrx1Tn18FDwJZenF9OjT6I80u4DT+xC4MGEFptATSkpgfDg0l5Wz+E5+WD8XAKWRls/kXkcJa1MmtakwUwPkv04sXdm15rZ2bW+H5irLK33tzszO...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwu/4P6wTW1tVdueMAAAAASUVORK5CYII='
with open(path, 'wb') as f:...
f.write(byte_data)
with open('test.png', 'rb') as f:
image_data = f.read()
with open('/Users/ethan/test2.png', 'wb') as f:
f.write(image_data)
操作系统OS模块
os.mkdir |
创建目录 |
os.rmdir |
删除目录 |
os.rename |
重命名 |
os.remove |
删除文件 |
os.getcwd |
获取当前工作路径 |
os.walk |
遍历目录 |
os.path.join |
连接目录与文件名 |
os.path.split |
分割文件名与目录 |
os.path.abspath |
获取绝对路径 |
os.path.dirname |
获取路径 |
os.path.basename |
获取文件名或文件夹名 |
os.path.splitext |
分离文件名与扩展名 |
os.path.isfile |
判断给出的路径是否是一个文件 |
os.path.isdir |
判断给出的路径是否是一个目录 |
os.path.abspath(dir_name/file_name)
$ pwd
/Users/ethan/coding/python
$ python
>>> import os # 记得导入 os 模块
>>> os.path.abspath('hello.py') # 获取文件绝对路径
'/Users/ethan/coding/python/hello.py'
>>> os.path.abspath('web')
'/Users/ethan/coding/python/web'
>>> os.path.abspath('.') # 当前目录的绝对路径
'/Users/ethan/coding/python'
os.path.dirname(dirXpath/fileXpath)
>>> os.path.dirname('/Users/ethan/coding/python/hello.py')#获取文件路径
'/Users/ethan/coding/python'
>>> os.path.dirname('/Users/ethan/coding/python/')#获取文件夹路径
'/Users/ethan/coding/python'
>>> os.path.dirname('/Users/ethan/coding/python')
'/Users/ethan/coding'
os.path.basename(Xpath)
>>> os.path.basename('/Users/ethan/coding/python/hello.py')#获取文件名
'hello.py'
>>> os.path.basename('/Users/ethan/coding/python/')#获取文件夹名
''
>>> os.path.basename('/Users/ethan/coding/python')
'python'
os.path.splitext(Xpath)
>>> os.path.splitext('/Users/ethan/coding/python/hello.py')#分割文件名和扩展名
('/Users/ethan/coding/python/hello', '.py')
>>> os.path.splitext('/Users/ethan/coding/python')
('/Users/ethan/coding/python', '')
>>> os.path.splitext('/Users/ethan/coding/python/')
('/Users/ethan/coding/python/', '')
os.path.split(Xpath)
>>> os.path.split('/Users/ethan/coding/python/hello.py')#分离目录和文件名
('/Users/ethan/coding/python', 'hello.py')
>>> os.path.split('/Users/ethan/coding/python/')
('/Users/ethan/coding/python', '')
>>> os.path.split('/Users/ethan/coding/python')
('/Users/ethan/coding', 'python')
os.path.isfile(Xpath)
os.path.isdir(Xpath)
>>> os.path.isfile('/Users/ethan/coding/python/hello.py')#判断是否为文件
True
>>> os.path.isdir('/Users/ethan/coding/python/')#是否为目录
True
>>> os.path.isdir('/Users/ethan/coding/python')
True
>>> os.path.isdir('/Users/ethan/coding/python/hello.py')
False
for xpath, dirname, filename in os.walk(Xpath):...
>>> for root, dirs, files in os.walk('/Users/ethan/coding'):
... print root
... print dirs
... print files
...
/Users/ethan/coding #绝对路径
['python'] #文件夹
[] #文件
/Users/ethan/coding/python
['web2']
['hello.py']
/Users/ethan/coding/python/web2
[]
[]
---------------------------------------------
import os
for root, dirs, files in os.walk("E://PYTHON//Basics//Fun", topdown=True):
print(root)
print(dirs)
print(files)
#结果
D:pythonpython.exe E:/PYTHON/Basics/Fun/HelloYoutube.py
E://PYTHON//Basics//Fun
['.idea', 'image', '__pycache__']
['Ball.py', 'Calculator.py', 'Editor.py', 'file.txt', 'HelloYoutube.py', 'tttGame.py']
E://PYTHON//Basics//Fun.idea
['inspectionProfiles']
['Fun.iml', 'misc.xml', 'modules.xml', 'workspace.xml']
E://PYTHON//Basics//Fun.ideainspectionProfiles
[]
['profiles_settings.xml']
E://PYTHON//Basics//Funimage
[]
['airship.png', 'city.png', 'cold.png', 'exit.png', 'hot.png', 'icon_love.png', 'lo.gif', 'open.png', 'plain.png', 'save.png']
E://PYTHON//Basics//Fun\__pycache__
[]
['Ball.cpython-39.pyc']
Process finished with exit code 0
-----------------------------------------
import os
for root, dirs, files in os.walk("E://PYTHON//Basics//Fun", topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
#结果
D:pythonpython.exe E:/PYTHON/Basics/Fun/HelloYoutube.py
E://PYTHON//Basics//Fun.ideainspectionProfilesprofiles_settings.xml
E://PYTHON//Basics//Fun.ideaFun.iml
E://PYTHON//Basics//Fun.ideamisc.xml
E://PYTHON//Basics//Fun.ideamodules.xml
E://PYTHON//Basics//Fun.ideaworkspace.xml
E://PYTHON//Basics//Fun.ideainspectionProfiles
E://PYTHON//Basics//Funimageairship.png
E://PYTHON//Basics//Funimagecity.png
E://PYTHON//Basics//Funimagecold.png
E://PYTHON//Basics//Funimageexit.png
E://PYTHON//Basics//Funimagehot.png
E://PYTHON//Basics//Funimageicon_love.png
E://PYTHON//Basics//Funimagelo.gif
E://PYTHON//Basics//Funimageopen.png
E://PYTHON//Basics//Funimageplain.png
E://PYTHON//Basics//Funimagesave.png
E://PYTHON//Basics//Fun\__pycache__Ball.cpython-39.pyc
E://PYTHON//Basics//FunBall.py
E://PYTHON//Basics//FunCalculator.py
E://PYTHON//Basics//FunEditor.py
E://PYTHON//Basics//Funfile.txt
E://PYTHON//Basics//FunHelloYoutube.py
E://PYTHON//Basics//Fun ttGame.py
E://PYTHON//Basics//Fun.idea
E://PYTHON//Basics//Funimage
E://PYTHON//Basics//Fun\__pycache__
Process finished with exit code 0
参考
explore-python/File-Dirctory