一、输出重定向到文件

>>> 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. 概率——17icpc西安

    不知道为什么是这样子的.. #include<bits/stdc++.h> using namespace std; int m,n; int main(){ while(scanf(&q ...

  2. Sqli labs系列-less-3 。。。

    原本想着找个搜索型的注入玩玩,毕竟昨天被实力嘲讽了 = = . 找了好长时间,我才发现,我没有 = = ,网上搜了一个存在搜索型注入的源码,我看了好长时间,楞没看出来从哪里搜索注入了....估计是我太 ...

  3. 关于提BUG的一点思考以及工作中总结的规范

    在测试的工作中,提BUG是日常工作. 以前自己为了省事,省时,仅仅是截图,在图片上注明一下问题,就放到BUG库中了. 现在发现这样会造成开发的时间的浪费,增加了沟通成本. 对于BUG,当发现了异常时, ...

  4. Appium 工作原理

    Appium - automation for mobile apps   一.Appium架构介绍 官网:www.appium.io 由SauceLab公司主持.并在Google的GATC2013会 ...

  5. 20140730 word标题样式 数组

    1.word 标题四, 右键更新 自己也可以新建标题样式 2.数组 连续内存,空间复杂度高(即使数组存在一个元素,占据的空间的大小不变),时间复杂度低(0(1)访问),内存分配一次性完成

  6. ThinkPHP5验证码不显示的原因及解决方法

    其实很久之前刚学习tp5框架的时候就遇到了这个问题,解决完后一直没再出过问题,今天用以前的框架做新项目时又碰到了这个问题,这里记录一下 问题原因: 1.TP5本就存在这个bug 2.数据库连接不正常( ...

  7. CF#541 D. Gourmet choice /// BFS 拓扑

    题目大意: 给定n m 第一行有n个数 第二行有m个数 接下来n行每行m列 有 = < > 位于 i j 的符号表示 第一行第i个数与第二行第j个数的大小关系 1.将n+m个数 当做按顺序 ...

  8. if控制器

    因为比较的是字符串,所以要在两边加双引号哦

  9. windows7远程连接服务器出现身份验证错误,又找不到加密Oracle修正

    把以下内容复制到文本中, Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Cur ...

  10. Linux 进程间通信 消息队列 实现两个进程间通信

    例子: 通过消息队列实现两个进程间通信,一个进程从终端输入数据,通过消息队列发送,另一个进程通过消息队列接收数据 文件1 创建进程1 终端输入通过消息队列发送数据 #include <stdio ...