一、输出重定向到文件

>>> with open('/home/f/py_script/passwd', 'rt+') as f1:
... print('Hello Dog!', file=f1)
...

二、参数列表的分拆

  当你要传递的参数已经是一个列表,但要调用的函数却接受分开一个个的参数值,这时候你要把已有的列表拆开来

>>> l
['cat', 1, 2, 3, 4]
>>> print(*l, sep=',') #更优雅的实现
cat,1,2,3,4
>>> print(','.join(str(x) for x in l))
cat,1,2,3,4

  以同样的方式,可以使用 ** 操作符分拆关键字参数为字典:

>>> def test(a, b, c='xxx'):
... print(a, b, c)
...
>>> d = {'a': 'dog', 'b': 'cat', 'c': 'horse'}
>>> test(**d) #以字典的values为参数
dog cat horse
>>> test(*d) #以字典的keys为参数
b c a
>>> test(*d.items()) #以字典的items为参数
('b', 'cat') ('c', 'horse') ('a', 'dog')

三、禁止输出换行符

>>> for x in a:
... print(x)
...
1
2
3
4
>>> for x in a:
... print(x, end=' ')
...
1 2 3 4

四、避免写入操作覆盖已有文件:open('/path/to/file', 'xt+')

>>> with open('/home/f/py_script/passwdtestsx', 'x+') as f:
... print('just a test!!', file=f)
...
>>> with open('/home/f/py_script/passwdtestsx', 'x+') as f:
... f.write('test once more!')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: '/home/f/py_script/passwdtestsx'

五、读写压缩的数据文件:gzip与bz2模块

>>> with gzip.open('/home/f/testdir/tmp.sh.gz', 'rt') as f:
... f.readline()
...
'#!/bin/bash\n'

#gzip.open()、bz2.open()的操作方式与open()一致,但默认是以二进制格式打开,即:[rwx]b[+]

六、处理路径名称:os.path.basename()、os.path.dirname()

>>> os.path.basename('/etc/fstab')
'fstab'
>>> os.path.dirname('/etc/fstab')
'/etc'

七、检测文件是否存在

os.path.isdir
os.path.isfile
os.path.islink
>>> os.path.realpath('/etc/mtab')    #若为软链接,则显示其指向的真实路径
'/proc/3079/mounts'
os.path.exists
os.path.getsize #获取文件大小
os.path.getctime
os.path.getmtime
>>> os.path.getatime('/etc/mtab')    #最近访问时间,默认显示自1970-01-01到当前时间的秒数
1470885109.0129082 
>>> import time
>>> time.ctime(os.path.getatime('/etc/mtab')) #转换时间格式
'Thu Aug 11 11:11:49 2016'

八、获取目录内容的列表:os.listdir()、os.path.join('', '', ''...)

#显示子目录列表
>>> [file for file in os.listdir('/home/f') if os.path.isdir(os.path.join('/home/f',file))]
['.pki', '.ssh', '.links', '.config', '.gnupg', '.vim', 'book', '.dbus', 'Public', 'Downloads']
#显示文件列表
>>> [file for file in os.listdir('/home/f') if os.path.isfile(os.path.join('/home/f',file))]
['.serverauth.1216', '.nvidia-settings-rc', '.xscreensaver', '.xinitrc', '.bashrc', '.bash_history']

Python3 From Zero——{最初的意识:005~文件和I/O}的更多相关文章

  1. Python3 From Zero——{最初的意识:000~Initial consciousness}

    http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000 a.编码 默认情况下,Python ...

  2. Python3 From Zero——{最初的意识:008~初级实例演练}

    一.构显国际橡棋8x8棋盘 #!/usr/bin/env python3 #-*- coding:utf-8 -*- color_0="\033[41m \033[00m" col ...

  3. Python3 From Zero——{最初的意识:006~数据编码与处理}

    一.读写CSV数据: #!/usr/bin/env python3 #-*- coding=utf8 -*- import csv with open('kxtx.csv', 'rt') as f: ...

  4. Python3 From Zero——{最初的意识:002~字符串和文本}

    一.使用多个界定符分割字符串 字符串.split(',')形式只适用于单一分割符的情况:多分割符同时应用的时候,可使用re.split() >>> line = 'asdf fjdk ...

  5. Python3 From Zero——{最初的意识:007~函数}

    一.编写可接受任意数量参数的函数:*.** >>> def test(x, *args, y, **kwargs): ... pass ... >>> test(1 ...

  6. Python3 From Zero——{最初的意识:004~迭代器和生成器}

    一.反向迭代:reversed() >>> a [1, 2, 3, 4] >>> for x in reversed(a): ... print(x, end=' ...

  7. Python3 From Zero——{最初的意识:003~数字、日期、时间}

    一.对数值进行取整:round(value,ndigits) >>> round(15.5,-1) #可以取负数 20.0 >>> round(15.5,0) #当 ...

  8. Python3 From Zero——{最初的意识:001~数据结构和算法}

    一.从队列两端高效插入.删除元素,及保留固定数量的数据条目: collections.deque([iterable[,maxlen=N]]) a = collections.deque([1, 2] ...

  9. 运行python “没有那个文件或目录3” 或 “/usr/local/bin/python3^M: bad interpreter: 没有那个文件或目录” 错误

    原因 如果使用的是#!/usr/local/bin/python3这种方式,就会出现 “/usr/local/bin/python3^M: bad interpreter: 没有那个文件或目录” 错误 ...

随机推荐

  1. 解决(Missing artifact com.oracle:ojdbc14:jar:11.2.0.4.0)

    maven项目检索时报Missing artifact com.oracle:ojdbc14:jar:11.2.0.4.0 经过查阅资料知道原因为: Oracle 的 ojdbc.jar 是收费的,M ...

  2. AcWing 201. 可见的点 (欧拉函数打表)打卡

    在一个平面直角坐标系的第一象限内,如果一个点(x,y)与原点(0,0)的连线中没有通过其他任何点,则称该点在原点处是可见的. 例如,点(4,2)就是不可见的,因为它与原点的连线会通过点(2,1). 部 ...

  3. 记录解决java.io.IOException: Server returned HTTP response code: 500 for URL:xxxxxxxx

    踩坑经历 因为项目需要去对接别的接口,使用URLConnection POST请求https接口,发送json数组时遇到java.io.IOException: Server returned HTT ...

  4. 分析由Python编写的大型项目(Volatility和Cuckoo)

    之前使用python都是用来做一些简单的脚本,本质上和bat批处理文件没有区别. 但是Python是可以用来编写大型的项目的,比如: Volatility:https://code.google.co ...

  5. 使用uc进行手机页面调试

    最近使用uc浏览器的时候发现了,一个有趣的现象,就是uc会处理h5web app为全屏,并屏蔽一些手机上的操作,这样就会使web app更加接近本地应用.所以就研究 了一下uc的手机调试. 1.准备工 ...

  6. 解决 html5 input type='number' 类型可以输入e

    当给 input 设置类型为 number 时,比如,我想限制,只能输入 0-9 的正整数,正则表达式如下: /^[-]?$/ // 匹配 0-9 的整数且只匹配 0 次或 1 次 用正则测试,小数点 ...

  7. Day 16 : Python 时间模块[time,]datetime[]及第三方模块的下载与安装

    在进行python程序开发时,除了可以使用python内置的标准模块外,还右许多第三方模块使用,可以在python官网找到. 在使用第三方模块时,需要下载并安装此模块,然后就可以使用标准模块一样导入并 ...

  8. 8-vim-移动命令-03-段落切换和括号切换

    1.段落切换 vi使用空行来区分段落 在程序开发时,通常一段功能相关的代码会写在一起--之间没有空行 命令 功能 { 上一段 } 下一段 2.括号切换 在程序世界中,() [] {}使用频率很高,而且 ...

  9. Avito Cool Challenge 2018 B - Farewell Party

    题目大意: 有n个人 接下来一行n个数a[i] 表示第i个人描述其他人有a[i]个的帽子跟他不一样 帽子编号为1~n 如果所有的描述都是正确的 输出possible 再输出一行b[i] 表示第i个人的 ...

  10. hdu6290奢侈的旅行

    高玩小Q不仅喜欢玩寻宝游戏,还喜欢一款升级养成类游戏.在这个游戏的世界地图中一共有n个城镇,编号依次为1到n. 这些城镇之间有m条单向道路,第i 条单项道路包含四个参数ui,vi,ai,bi,表示一条 ...