Python 文件操作, 字典, SET和函数
本文的Python知识基于 Python3
循环语句
- 循环语句可以使用
break来跳出 循环语句可以有
else语句- else 语句块是在
循环条件不成立的时候执行的 - 通过
break跳出的循环不会执行else语句块
- else 语句块是在
文件操作
在Python中, 可以通过help()函数来查询文档
通过
open()函数打开文件- f_obj = open("demo.txt")
- open函数第一个参数是文件路径, 可以是相对路径, 也可以是绝对路径
- 第二个参数是打开方式, 如不传递, 则默认是
r, 也就是只读
file object = open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)mode
拥有如下操作:
| 值 | 意义 |
|---|---|
| 'r' | 只读 (默认) |
| 'w' | 只写, 会先清空文件内容 |
| 'x' | 创建一个新文件并写入 |
| 'a' | 写入模式, 如果文件有内容则从末尾追加 |
| 'b' | 二进制模式 |
| 't' | 文本模式(默认) |
| '+' | 更新模式(读写) |
| 'U' | 通用换行模式 (不推荐) |
常用值以及意义见下列表
| 模式 | 描述 |
|---|---|
| r | 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 |
| rb | 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。 |
| r+ | 打开一个文件用于读写。文件指针将会放在文件的开头。 |
| rb+ | 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。 |
| w | 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
| wb | 以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
| w+ | 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
| wb+ | 以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
| a | 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 |
| ab | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 |
| a+ | 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 |
| ab+ | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。 |
buffering
- 如果buffering的值被设为0, 表示无缓冲(只能在二进制模式下)
- 如果buffering的值被设为1, 表示行缓冲(只能在文本模式下)
- 如果buffering的值被设为 > 1, 表示分配指定的大小
- 如果buffering的值不设置(默认-1), 则寄存区的缓冲大小则为系统默认
encoding
- 文件的编码
- 只能在文本模式下使用
- 默认是系统编码
newlines
换行符
- 'r'
- 'n'
- 'rn'
>>> f_obj = open('demo.txt') # 打开demo.txt, 以只读方式
>>> type(f_obj)
<class '_io.TextIOWrapper'>
>>> f_obj.readline() # 读一行
'admin admin\n'
>>> f_obj.readline() # 读一行
'root root\n'
>>> f_obj.readline() # 读一行
'hxhlb hxhlb\n'
>>> f_obj.readline() # 读一行
'001 001\n'
>>> f_obj.readline() # 读一行
''
>>> f_obj.readline() # 读一行
''
>>> f_obj.seek(0) # 文件游标重新回到文件头
0
>>> f_obj.readlines() # 全部读取 返回list
['admin admin\n', 'root root\n', 'hxhlb hxhlb\n', '001 001\n']
>>> f_obj.close() # 关闭文件
>>> file对象的常用函数
| 序号 | 方法及描述 |
|---|---|
| 1 | <p>file.close()</p><p>关闭文件。关闭后文件不能再进行读写操作。</p> |
| 2 | <p>file.flush()</p><p>刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。</p> |
| 3 | <p>file.fileno()</p><p> 返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。</p> |
| 4 | <p>file.isatty()</p><p>如果文件连接到一个终端设备返回 True,否则返回 False。</p> |
| 5 | <p>file.next()</p><p>返回文件下一行。</p> |
| 6 | <p>file.read([size])</p><p>从文件读取指定的字节数,如果未给定或为负则读取所有。</p> |
| 7 | <p>file.readline([size])</p><p>读取整行,包括 "n" 字符。</p> |
| 8 | <p>file.readlines([sizeint])</p><p>读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。</p> |
| 9 | <p>file.seek(offset[, whence])</p><p>设置文件当前位置</p> |
| 10 | <p>file.tell()</p><p>返回文件当前位置。</p> |
| 11 | <p>file.truncate([size])</p><p>从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后 V 后面的所有字符被删除,其中 Widnows 系统下的换行代表2个字符大小。 </p> |
| 12 | <p>file.write(str)</p><p>将字符串写入文件,没有返回值。</p> |
| 13 | <p>file.writelines(sequence)</p><p>向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。</p> |
字典
- 以
{}括起来, 元素之间使用逗号分隔 mydict = {'key1':'value1', 'key2': 2, 3 : 'xx'}- 键和值都可以是任意基础类型
- 通过
键访问值 mydict['key1']mydict[3]
>>> mydict = { 'hxhlb' : ['hxhlb', 28, True, [30, 30, 30]], 2 : 2333, '3' : 'xxx' }
>>> mydict
{'hxhlb': ['hxhlb', 28, True, [30, 30, 30]], 2: 2333, '3': 'xxx'}
>>> mydict['hxhlb'] # 访问
['hxhlb', 28, True, [30, 30, 30]]
>>> mydict[2]
2333
>>> mydict['3']
'xxx'
>>> mydict['x'] = "asdf" # 新增一个key
>>> mydict
{'hxhlb': ['hxhlb', 28, True, [30, 30, 30]], 2: 2333, '3': 'xxx', 'x': 'asdf'}
>>> mydict['x'] = "xxxxxx" # 修改一个key
>>> mydict
{'hxhlb': ['hxhlb', 28, True, [30, 30, 30]], 2: 2333, '3': 'xxx', 'x': 'xxxxxx'}
>>> mydict['xxxx']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'xxxx'
>>> 'xxxx' in mydict # 查询key在不在字典中
False
>>> 2 in mydict # 查询key在不在字典中
True
>>> mydict.get(2) # 获取指定key的值
2333
>>> mydict.get('x')
'xxxxxx'
>>> mydict.get(1)
>>> mydict.get(2, 'None') # 获取指定key的值, 没有则返回默认值
2333
>>> mydict.get('x', 'None')
'xxxxxx'
>>> mydict.get(1, 'None')
'None'
>>> mydict.pop('x') # 删除指定的key
'xxxxxx'
>>> mydict
{'hxhlb': ['hxhlb', 28, True, [30, 30, 30]], 2: 2333, '3': 'xxx'}
>>> mydict.keys() # 所有的key
dict_keys(['hxhlb', 2, '3'])
>>> mydict.values() # 所有的value
dict_values([['hxhlb', 28, True, [30, 30, 30]], 2333, 'xxx'])
>>> mydict.items() # 所有的键值
dict_items([('hxhlb', ['hxhlb', 28, True, [30, 30, 30]]), (2, 2333), ('3', 'xxx')])
>>> Set
- 它是不重复的
- 它以
set([ ])包含 - 使用
,隔开
>>> myset = set([1,1,1,2,2,2,3,3,3,4,4,5])
>>> myset
{1, 2, 3, 4, 5}
>>> type(myset)
<class 'set'>
>>> myset.add(6)
>>> myset
{1, 2, 3, 4, 5, 6}
>>> myset.add(1)
>>> myset
{1, 2, 3, 4, 5, 6}
>>> myset.remove(1)
>>> myset
{2, 3, 4, 5, 6}
>>> myset1 = set([1,2,3,4])
>>> myset2 = set([2,3,4,5])
>>> type(myset1)
<class 'set'>
>>> type(myset2)
<class 'set'>
>>> myset1 & myset2
{2, 3, 4}
>>> myset1 | myset2
{1, 2, 3, 4, 5}
>>> 函数
函数的调用就不多说了..
定义函数
def 函数名(参数列表) :
函数体
def myfunc(x):
print (x)
def myfunc2(x, y):
print(x)
print(y)>>> def func1() :
... print("MyFunc")
...
>>> def func2(x):
... print(x)
...
>>> def func3(x, y):
... print(x)
... print(y)
...
>>> func1()
MyFunc
>>> func2(1)
1
>>> func2("Hades")
Hades
>>> func3(1,2)
1
2
>>> func3(1.0, 2)
1.0
2
>>> func3('Hades', 2)
Hades
2
>>> 需要注意的问题
看下面的例子:
>>> def func1(x, y):
... y = x / 2
... print(y)
...
>>> func1('123', '4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func1
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>> def func1(x, y):
... y = int(x) / 2
... print(y)
...
>>> func1('123', '4')
61.5
>>> func1('abc', '4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func1
ValueError: invalid literal for int() with base 10: 'abc'
>>> 这样, 我们就来改进一下
>>> def func1(x, y):
... if not isinstance(x, int): # 判断 x 是不是 int
... print("参数错误!")
... return
... y = int(x) / 2
... print(y)
...
>>> func1('123', '4')
参数错误!
>>> func1('abc', '4')
参数错误!
>>> func1(444, '2')
222.0
>>> 返回值
在函数中, 我们使用
return返回- 如果 return 后无参数, 则直接退出方法
- 否则, 退出方法并返回参数
>>> def func(x, y):
... if not isinstance(x, int): # 判断 x 是不是 int
... print("参数错误!")
... return 0
... y = int(x) / 2
... return y
...
>>> ret = func('123', '4')
参数错误!
>>> print(ret)
0
>>> ret = func('abc', '4')
参数错误!
>>> print(ret)
0
>>> ret = func(444, '2')
>>> print(ret)
222.0
>>> Python中, return 可以返回多个值
>>> def func(x, y):
... if not isinstance(x, int): # 判断 x 是不是 int
... print("参数错误!")
... return 0, 0
... y = int(x) / 2
... return x, y
...
>>> retx, rety = func('123', '4')
参数错误!
>>> print(retx, rety)
0 0
>>> retx, rety = func('abc', '4')
参数错误!
>>> print(retx, rety)
0 0
>>> retx, rety = func(444, '2')
>>> print(retx, rety)
444 222.0
>>>
>>> def func(x, y):
... if not isinstance(x, int): # 判断 x 是不是 int
... print("参数错误!")
... return 0, 0, 0
... y = int(x) / 2
... return x, y, -1
...
>>> retx, rety, retz = func('123', '4')
参数错误!
>>> print(retx, rety, retz)
0 0 0
>>> retx, rety, retz = func('abc', '4')
参数错误!
>>> print(retx, rety, retz)
0 0 0
>>> retx, rety, retz = func(444, '2')
>>> print(retx, rety, retz)
444 222.0 -1
>>> 不推荐返回多个值, 完全可以返回一个list或其他的东西
默认参数
我们可以给参数规定一个默认值, 简化调用
>>> def func(x, y = 100):
... if not isinstance(x, int): # 判断 x 是不是 int
... print("参数错误!")
... return 0, 0
... y = int(x) / 2
... return x, y
...
>>> retx, rety = func('123')
参数错误!
>>> print(retx, rety)
0 0
>>> retx, rety = func('abc')
参数错误!
>>> print(retx, rety)
0 0
>>> retx, rety = func(444)
>>> print(retx, rety)
444 222.0
>>> 注意, Python3中, 默认参数都是在最后的, 默认参数后的所有参数都有默认值
>>> def func(x, y = 100, z = 1000, o):
File "<stdin>", line 1
def func(x, y = 100, z = 1000, o):
^
SyntaxError: unexpected EOF while parsing
>>> if not isinstance(x, int): # 判断 x 是不是 int
... print("参数错误!")
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> return 0, 0
File "<stdin>", line 1
SyntaxError: 'return' outside function
>>> y = int(x) / 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> return x, y
File "<stdin>", line 1
SyntaxError: 'return' outside function
>>> retx, rety = func('123')
参数错误!
>>> print(retx, rety)
0 0
>>> retx, rety = func('abc')
参数错误!
>>> print(retx, rety)
0 0
>>> retx, rety = func(444)
>>> print(retx, rety)
444 222.0
>>> def func(x, y = 100, z = 1000, o = 0):
... if not isinstance(x, int): # 判断 x 是不是 int
... print("参数错误!")
... return 0, 0
... y = int(x) / 2
... return x, y
...
>>> retx, rety = func('123')
参数错误!
>>> print(retx, rety)
0 0
>>> retx, rety = func('abc')
参数错误!
>>> print(retx, rety)
0 0
>>> retx, rety = func(444)
>>> print(retx, rety)
444 222.0
>>> 不同的调用方式
可以在调用的时候, 指定某个参数的值
>>> def func(x = 0, y = 100, z = 1000, o = 0):
... if not isinstance(x, int): # 判断 x 是不是 int
... print("参数错误!")
... return 0, 0
... y = int(x) / 2
... return x, y
...
>>> retx, rety = func(x = '100')
参数错误!
>>> print(retx, rety)
0 0
>>> retx, rety = func(x = 10)
>>> print(retx, rety)
10 5.0
>>> retx, rety = func(x = 10, y = 20)
>>> print(retx, rety)
10 5.0
>>> retx, rety = func(y = 30)
>>> print(retx, rety)
0 0.0
>>> retx, rety = func(444)
>>> print(retx, rety)
444 222.0
>>> retx, rety = func()
>>> print(retx, rety)
0 0.0
>>> 未完待续...
如有错误,请提出指正!谢谢.
本文由 花心胡萝卜 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: 2017-07-13 at 01:58 pm