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
'

#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']
原文地址:https://www.cnblogs.com/hadex/p/5761939.html