python文件和异常

 


文件和异常

  • 使用vscode时需要选中文件夹按ctrl+k,接着按ctrl+o

python中异常的关系结构

BaseException
│
├── SystemExit
│
├── KeyboardInterrupt
│
├── GeneratorExit
│
└── Exception
    │
    ├── StopIteration
    │
    ├── ArithmeticError
    │   ├── ZeroDivisionError
    │   ├── OverflowError
    │   └── FloatingPointError
    │
    ├── AssertionError
    │
    ├── AttributeError
    │
    ├── BufferError
    │
    ├── EOFError
    │
    ├── ImportError
    │   └── ModuleNotFoundError
    │
    ├── LookupError
    │   ├── IndexError
    │   └── KeyError
    │
    ├── MemoryError
    │
    ├── NameError
    │   ├── UnboundLocalError
    │
    ├── OSError
    │   ├── FileNotFoundError
    │   ├── PermissionError
    │   ├── IsADirectoryError
    │   ├── NotADirectoryError
    │   ├── InterruptedError
    │   └── BlockingIOError
    │
    ├── ReferenceError
    │
    ├── RuntimeError
    │   ├── NotImplementedError
    │   └── RecursionError
    │
    ├── SyntaxError
    │   ├── IndentationError
    │   └── TabError
    │
    ├── SystemError
    │
    ├── TypeError
    │
    ├── ValueError
    │   ├── UnicodeError
    │   │   ├── UnicodeDecodeError
    │   │   ├── UnicodeEncodeError
    │   │   └── UnicodeTranslateError
    │
    ├── Warning
    │   ├── DeprecationWarning
    │   ├── PendingDeprecationWarning
    │   ├── RuntimeWarning
    │   ├── SyntaxWarning
    │   ├── UserWarning
    │   ├── FutureWarning
    │   ├── ImportWarning
    │   ├── UnicodeWarning
    │   ├── BytesWarning
    │   └── ResourceWarning
    │
    └── PermissionError

内置函数open()

读和写文件

open() 将会返回一个 file 对象,基本语法格式如下:

open(filename, mode)
  • filename:包含了你要访问的文件名称的字符串值。
  • mode:决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
模式 描述
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
w+ 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

f.write()

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "w")

f.write( "Python 是一个非常好的语言。\n是的,的确非常好!!\n" )

# 关闭打开的文件
f.close()
返回写入字符的数量
#返回写入到文件中的字符数量
#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "w")

num = f.write( "Python 是一个非常好的语言。\n是的,的确非常好!!\n" )
print(num)
# 关闭打开的文件
f.close()
写入的不是字符串需要转换
#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo1.txt", "w")

value = ('www.runoob.com', 14)
s = str(value)
f.write(s)

# 关闭打开的文件
f.close()

f.read()

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

str = f.read()
print(str)

# 关闭打开的文件
f.close()

f.readline()

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

#会从文件中读取单独的一行。换行符为 '\n'。f.readline() 如果返回一个空字符串, 说明已经已经读取到最后一行。
str = f.readline()
print(str)

# 关闭打开的文件
f.close()

f.readlines()

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

# 将返回该文件中包含的所有行。
str = f.readlines()
print(str)

# 关闭打开的文件
f.close()

迭代读取每行

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

for line in f:
    print(line, end='')

# 关闭打开的文件
f.close()

f.tell()

f.tell() 用于返回文件当前的读/写位置(即文件指针的位置)。文件指针表示从文件开头开始的字节数偏移量。f.tell() 返回一个整数,表示文件指针的当前位置。

f.seek()

如果要改变文件指针当前的位置, 可以使用 f.seek(offset, from_what) 函数。

f.seek(offset, whence) 用于移动文件指针到指定位置。

offset 表示相对于 whence 参数的偏移量,from_what 的值, 如果是 0 表示开头, 如果是 1 表示当前位置, 2 表示文件的结尾,例如:

  • seek(x,0) : 从起始位置即文件首行首字符开始移动 x 个字符
  • seek(x,1) : 表示从当前位置往后移动x个字符
  • seek(-x,2):表示从文件的结尾往前移动x个字符

from_what 值为默认为0,即文件开头。下面给出一个完整的例子:

>>> f = open('/tmp/foo.txt', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)     # 移动到文件的第六个字节
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # 移动到文件的倒数第三字节
13
>>> f.read(1)
b'd'

f.close()

在文本文件中 (那些打开文件的模式下没有 b 的), 只会相对于文件起始位置进行定位。

当你处理完一个文件后, 调用 f.close() 来关闭文件并释放系统的资源,如果尝试再调用该文件,则会抛出异常。

>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file

pathlib模块

  • Python 提供了 pathlib 模块,让你能够更轻松地在各种操作系统中处理文件和目录。提供特定功能的模块通常称为库(library)。这就是这个模块被命名为 pathlib 的原因所在。

读取文件

  • 要使用文本文件中的信息时,首先要将信息读取到内存中,既可以读取文件中的全部内容,也可以逐行读取。

  • 要使用文件的内容,需要将其路径告诉python。路径(path)指的是文件或文件夹在系统中的准确位置。

Path()
read_text()
#!/usr/bin/python3
#_*_coding:utf-8_*_

from pathlib import Path

#Path()指定读取文件的路径
path = Path('/server/python/py_files/pi_digits.txt')
#path.read_text()读取文件内容加载到内存
contents = path.read_text()
  • 简单示例
#!/usr/bin/python3
#_*_coding:utf-8_*_

from pathlib import Path

path = Path('pi_digits.txt')
contents = path.read_text()
pi_string = ''
for line in contents.splitlines():
    pi_string += line.lstrip()
print(pi_string)
print(len(pi_string))

写入文件

  • 在使用write_text()时,务必谨慎,如果指定的文件已经存在,write_text()会删除其内容,并将指定的内容写入其中,后面案例使用pathlib检查文件是否存在。
write_text() 单行写入
  • 注意:python只能将字符串写入文件,如果要将数值数据写入到文件中,必须先使用str()将数据转为字符串格式
#!/usr/bin/python3
#_*_coding:utf-8_*_

from pathlib import Path
import math

path = Path('pi_digits.txt')
path.write_text('{:.30f}'.format(math.pi))
path.write_text('123')
write_text() 多行写入
  • 要将多行写入文件,需要创建一个字符串(该字符串包含要写入文件的全部内容),再调用write_text()并将字符串传递给它.
#!/usr/bin/python3
#_*_coding:utf-8_*_

from pathlib import Path

contents = '我'
contents += '叫'
contents += 'jiaxing'

path = Path('programming.txt')
path.write_text(contents)

path.exists()

  • 判断文件是否存在,存在返回True,不存在返回Flase
#!/usr/bin/python3
#_*_coding:utf-8_*_

from pathlib import Path
import json

path = Path('username.json')
if path.exists():
    contents = path.read_text()
    username = json.loads(contents)
    print(f"您好 {username}")
else:
    username = input("输入你的名字: ")
    contents = json.dumps(username)
    path.write_text(contents)
    print(f"您好 {username}")

json格式文件存储数据

模块 json 让你能够将简单的 Python 数据结构转换为 JSON 格式的字符串,并在程序再次运行时从文件中加载数据。你还可以使用 json 在 Python 程序之间共享数据。更重要的是,JSON 数据格式并不是 Python 专用的,这让你能够将以 JSON 格式存储的数据与使用其他编程语言的人共享。这是一种轻量级数据格式,不仅很有用,也易于学习。

json.dumps()和json.loads()

  • json.dumps()用来存储数据
  • json.loads()用来读取这些数据

json.dumps()函数接受一个实参,即要转换为json格式的数据。这个函数会返回一个字符串,我们可以将这个字符串写入到文件:

#!/usr/bin/python3
#_*_coding:utf-8_*_

from pathlib import Path
import json

numbers = [1,2,3,4,5]
path = Path('numbers.json')
contents = json.dumps(numbers)
path.write_text(contents)

-->>写入json文件内容:
root@jiaxing:/server/python# cat numbers.json 
[1, 2, 3, 4, 5]

json.loads()将json文件中的列表读取到内存中:

#!/usr/bin/python3
#_*_coding:utf-8_*_

from pathlib import Path
import json

path = Path('numbers.json')
contents = path.read_text()
numbers = json.loads(contents)
print(numbers)

-->>输出:
root@jiaxing:/server/python# python3 number_reader.py 
[1, 2, 3, 4, 5]

json.dump()和json.load()

  • dumps()函数还有一个变体, dump(),它只将对象序列化为 text file 。因此,如果 f 是 text file对象,可以这样做:
#!/usr/bin/python3
#_*_coding:utf-8_*_

import json


x = [1, 'simple', 'list']
with open('file.txt','w') as f:
    json.dump(x,f)

with open('file.txt','r') as f:
    print(json.load(f))

查找文件

1) os.listdir()遍历

In [4]: [ item for item in os.listdir('.') if item.endswith('.txt') ]
Out[4]: ['22.txt', '11.txt']

2) fnmatch()库遍历

In [1]: import os

In [2]: import fnmatch

In [3]: [ name for name in os.listdir('.') if fnmatch.fnmatch(name,'*.txt') ]
Out[3]: ['22.txt', '2cc.txt', '11.txt', 'aa.txt']

In [5]: [ name for name in os.listdir('.') if fnmatch.fnmatch(name,'[a-z]*.txt') ]
Out[5]: ['aa.txt']

In [6]: [ name for name in os.listdir('.') if fnmatch.fnmatch(name,'[!a-z]*.txt') ]
Out[6]: ['22.txt', '2cc.txt', '11.txt']

3) glob()

In [7]: import glob

In [8]: glob.glob('*.txt')
Out[8]: ['22.txt', '2cc.txt', '11.txt', 'aa.txt']

异常处理

  • except 子句 可以用带圆括号的元组来指定多个异常,例如:
... except (RuntimeError, TypeError, NameError):
...     pass
  • raise 语句支持强制触发指定的异常。例如:
>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    raise NameError('HiThere')
NameError: HiThere
  • raise 如果传递的是异常类,将通过调用没有参数的构造函数来隐式实例化:
raise ValueError  # 'raise ValueError()' 的简化
  • 如果只想判断是否触发了异常,但并不打算处理该异常,则可以使用更简单的 raise 语句重新触发异常:
>>> try:
...    	raise NameError('HiThere')
...	except NameError:
...    	print('An exception flew by!')
...    	raise
...
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    raise NameError('HiThere')
NameError: HiThere
posted @   逃离这世界~  阅读(7)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示

目录导航