Linux Shell 我们要操作一个文件很简单,如果是通过python来读写文件呢?这里介绍下python的文件操作!
1. python 读文件
2. python 写文件
3. python 实现文件内容替换
python 操作文件可以用file 或 open 函数,如用file,也是通过调用open函数来实现操作。默认的模式是读,另外完整的其它模式有
r 只读; r+ 读写; w, 只写,会覆盖文件 ;w+ 读写; a 追加; a+ ,读写,追加
>>> path = '/root/py_scripts/temp/test'
>>> f = open(path) #默认是 r 模式
>>> f.readlines() #readlines() 打印出文件所有行,同read()
['first 111111\n', 'second 222222\n', 'red red red \n', 'yellow bule \n']
>>> f.readlines()
[]
>>> f = open(path)
>>> f.readline() #每次往下打印一行
'first 111111\n'
>>> f.readline()
'second 222222\n'
# f.read() 同 f.readlines(),另外文件内容只能实现一次打印
>>> newfile = '/root/py_scripts/temp/new'
>>> f = open(newfile,'w') # 写模式
>>> f.write('hello world!')
>>> f.flush() # flush() 把内存的数据刷新到文件中,通常内存会保留部分字节,好像是1024byte. 大于这个值就会主动刷新写入到文件。否则需要手动刷新,才看的到内容。
>>> f.close() #所有操作执行完,需要关闭文件句柄
>>> path = '/root/py_scripts/temp/test'
>>> import fileinput
>>> for line in fileinput.input(path,backup='test.bak',inplace=1): #backup 备份,inplace=1 无输出, inplace=0 有输出
... line = line.replace('hello', 'hi')
... print line