Python用法速查@文件操作

文本文件

os.path.exists('path/file.txt')

>>>os.path.exists("C://ArcMentalTest//config.txt")
True

f=open(path, mode)

data=f.read()

r
w
a追加
b二进制
+读/写
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\t1\t9\t9\n', '6\t3\t2\t8\n', '20\t10\t3\t23\n', '1\t4\t1\t10\n', '10\t8\t6\t3\n', '10\t2\t1\t6']
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 .\n', 'a file named file.txt\n', '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\t1\t9\t9\n', '6\t3\t2\t8\n', '20\t10\t3\t23\n', '1\t4\t1\t10\n', '10\t8\t6\t3\n', '10\t2\t1\t6']

f.write('message\n')

with open('/Users/ethan/data2.txt', 'w') as f:
    f.write('one\n') #覆盖写,文件不存在则创建
    f.write('two')


with open('/Users/ethan/data2.txt', 'a') as f: #追加写
    f.write('three\n')
    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\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\xce\x00\x00\x00\xc8\x08\x06\x00\x00\x00\xa0F\xde\xd9\x00\x00\t\xb6IDATx\x9c\xed\xddAk\x1b\xcd\x1d\xc7q\xbd\x04\xbf\x82\xd5\x84\x1eJz(\x82\\J!`z\xf1\xd59\...\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x000\xbb\xfe\x0f\xeb\x04\xd6\xd6\xd5]\xb9\xe3\x00\x00\x00\x00IEND\xaeB`\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:\python\python.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\.idea\inspectionProfiles
[]
['profiles_settings.xml']
E://PYTHON//Basics//Fun\image
[]
['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:\python\python.exe E:/PYTHON/Basics/Fun/HelloYoutube.py
E://PYTHON//Basics//Fun\.idea\inspectionProfiles\profiles_settings.xml
E://PYTHON//Basics//Fun\.idea\Fun.iml
E://PYTHON//Basics//Fun\.idea\misc.xml
E://PYTHON//Basics//Fun\.idea\modules.xml
E://PYTHON//Basics//Fun\.idea\workspace.xml
E://PYTHON//Basics//Fun\.idea\inspectionProfiles
E://PYTHON//Basics//Fun\image\airship.png
E://PYTHON//Basics//Fun\image\city.png
E://PYTHON//Basics//Fun\image\cold.png
E://PYTHON//Basics//Fun\image\exit.png
E://PYTHON//Basics//Fun\image\hot.png
E://PYTHON//Basics//Fun\image\icon_love.png
E://PYTHON//Basics//Fun\image\lo.gif
E://PYTHON//Basics//Fun\image\open.png
E://PYTHON//Basics//Fun\image\plain.png
E://PYTHON//Basics//Fun\image\save.png
E://PYTHON//Basics//Fun\__pycache__\Ball.cpython-39.pyc
E://PYTHON//Basics//Fun\Ball.py
E://PYTHON//Basics//Fun\Calculator.py
E://PYTHON//Basics//Fun\Editor.py
E://PYTHON//Basics//Fun\file.txt
E://PYTHON//Basics//Fun\HelloYoutube.py
E://PYTHON//Basics//Fun\tttGame.py
E://PYTHON//Basics//Fun\.idea
E://PYTHON//Basics//Fun\image
E://PYTHON//Basics//Fun\__pycache__

Process finished with exit code 0

参考

explore-python/File-Dirctory

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JFLEARN

CSDN这么拉会有人打赏?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值