Python3 From Zero——{最初的意识:005~文件和I/O}
一、输出重定向到文件
>>> 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}的更多相关文章
- Python3 From Zero——{最初的意识:000~Initial consciousness}
http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000 a.编码 默认情况下,Python ...
- Python3 From Zero——{最初的意识:008~初级实例演练}
一.构显国际橡棋8x8棋盘 #!/usr/bin/env python3 #-*- coding:utf-8 -*- color_0="\033[41m \033[00m" col ...
- Python3 From Zero——{最初的意识:006~数据编码与处理}
一.读写CSV数据: #!/usr/bin/env python3 #-*- coding=utf8 -*- import csv with open('kxtx.csv', 'rt') as f: ...
- Python3 From Zero——{最初的意识:002~字符串和文本}
一.使用多个界定符分割字符串 字符串.split(',')形式只适用于单一分割符的情况:多分割符同时应用的时候,可使用re.split() >>> line = 'asdf fjdk ...
- Python3 From Zero——{最初的意识:007~函数}
一.编写可接受任意数量参数的函数:*.** >>> def test(x, *args, y, **kwargs): ... pass ... >>> test(1 ...
- Python3 From Zero——{最初的意识:004~迭代器和生成器}
一.反向迭代:reversed() >>> a [1, 2, 3, 4] >>> for x in reversed(a): ... print(x, end=' ...
- Python3 From Zero——{最初的意识:003~数字、日期、时间}
一.对数值进行取整:round(value,ndigits) >>> round(15.5,-1) #可以取负数 20.0 >>> round(15.5,0) #当 ...
- Python3 From Zero——{最初的意识:001~数据结构和算法}
一.从队列两端高效插入.删除元素,及保留固定数量的数据条目: collections.deque([iterable[,maxlen=N]]) a = collections.deque([1, 2] ...
- 运行python “没有那个文件或目录3” 或 “/usr/local/bin/python3^M: bad interpreter: 没有那个文件或目录” 错误
原因 如果使用的是#!/usr/local/bin/python3这种方式,就会出现 “/usr/local/bin/python3^M: bad interpreter: 没有那个文件或目录” 错误 ...
随机推荐
- NOIp2018集训test-10-22 (联考六day2)
中间值 两个log肯定会被卡.我用的第一种做法,就是要各种特判要在两个序列都要二分比较麻烦. //Achen #include<bits/stdc++.h> #define For(i,a ...
- Spring Boot下启用https
1.需要一个证书,可以自己生成或者购买.下面是我们通过keytool自己生成. 打开运行,输入cmd,进入命令行 输入生成命令: keytool -genkey -alias tomcat -stor ...
- angularjs 中 Factory,Service,Provider 之间的区别
本片文章是使用了 angularjs 中使用 service 在controller 之间 share 对象和数据 的code(http://jsfiddle.net/kn46u0uj/1/) 来进行 ...
- word中怎样把文档里的中文以及中文字符全选?
word中怎样把文档里的中文以及中文字符全选? 参考: 百度 案例: 有个文档是中英文混杂的 现在需要把中文以及中文字符全部设置成别的颜色 应该怎样操作? 有80多页 别说让我一个一个的设置 以wor ...
- Redis启动Sentinel出现警告的解决
Redis 3.0.7版本启动时出现警告的解决办法 7283:M 12 Mar 12:13:33.749 # WARNING: The TCP backlog setting of 511 canno ...
- HDU 4109 Instrction Arrangement
题目链接:https://vjudge.net/problem/HDU-4109 题目大意 有 N 个指令,标号从 0 ~ N - 1,和 M 个指令间的先后关系,每个关系都有一个权值 w,表示后一个 ...
- SQL Serve2008的一些操作
今天花了一下午的时间在熟悉SQL serve的一些操作,在此记录下学习到的东西: 首先创建数据库: use master --设置当前数据库为master,以便方便访问表sysdatabases if ...
- 关于Visual Leak Detector的配置与使用 (测试vector 引起的内存泄漏问题)
之前在做一个音频特征提取的批量处理程序,老是出现内存泄露问题,用Visual Leak Detector(VLD)工具做了下检测,检测出了一些问题,解决后还是会有问题.之后继续排查,因为我的代码中,大 ...
- Spring Boot Restful WebAPI集成 OAuth2
系统采用前后端分离的架构,采用OAuth2协议是很自然的事情. 下面开始实战,主要依赖以下两个组件: <dependency> <groupId>org.springframe ...
- MySQL 到底是怎么解决幻读的?
; 原理:将历史数据存一份快照,所以其他事务增加与删除数据,对于当前事务来说是不可见的. 2. next-key 锁 (当前读) next-key 锁包含两部分: 记录锁(行锁) 间隙锁 记录锁是加在 ...