文件读取
f = open('data.txt', 'r')
print(f.read())
f.seek(0)
print(f.tell())
print(f.read(6))
print(f)
print('文件名为: ', f.name)
print('文件描述符为:', f.fileno)
print('是否连接到一个终端设备:', f.isatty())
print('文件是否关闭:', f.closed())
f.close()
f = open("data.txt",'rb+')
byt = f.read()
print(byt)
print("\n转换后:")
print(byt.decode('utf-8'))
f.close()
f = open('data.txt', 'r')
byt = f.readline()
print(byt)
f.seek(0,0)
byt = f.readline(7)
print(byt)
print(f.read())
f.seek(0, 0)
byt = f.readlines()
print(byt)
f.seek(0, 0)
byt = f.readlines(7)
print(byt)
print('当前位置: %d' % f.tell())
f.seek(0, 0)
f.truncate(20)
print('文件内容:', f.readlines())
f.close()
文件写入
f = open('data.txt', 'w+')
f.write('Hello World!\nlizhong\npython\n')
f.writelines(['菜鸟教程\n', '中文说明'])
f.flush()
f.close()
上下文管理器
with 表达式 [as target]: ??代码块
with open('data.txt', 'w+') as f:
f.write('\nPython 教程')
sys模块 os模块
>>> import os
>>> os.getcwd()
>>> os.chdir('/Users/lizhong/Downloads')
>>> os.getcwd()
pickle 模块
pickle 模块
import pickle
tup1 = ('I love Python', {1,2,3}, None)
p1 = pickle.dumps(tup1)
print(p1)
t2 = pickle.loads(p1)
print(p2)
import pickle
tup2 = ('I love Python', {1,2,3}, None)
with open('a.txt', 'wb') as f:
pickle.dump(tup2, f)
with open('a.txt', 'rb') as f:
t3 = pickle.load(f)
print(t3)
fileinput 模块
fileinput 模块
1. 从标准输入中读取 当你的 Python 脚本没有传入任何参数时,fileinput 默认会以 stdin 作为输入源。
import fileinput
for line in fileinput.input():
print(line)
2. 单独打开一个文件
import fileinput
with fileinput.input(files=('a.txt',)) as file:
for line in file:
print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='')
3. 批量打开多个文件 将 lineno() 改为 filelineno() 显示原文件真实行号。
import fileinput
with fileinput.input(files=('a.txt', 'data.txt')) as file:
for line in file:
print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='')
搭配 glob 模块使用绝配。
import fileinput
import glob
for line in fileinput.input(glob.glob("*.txt")):
if fileinput.isfirstline():
print('-'*20, f'Reading {fileinput.filename()}...', '-'*20)
print(str(fileinput.lineno()) + ': ' + line.upper(), end="")
4. 读取时备份文件
import fileinput
with fileinput.input(files=("a.txt",), backup=".bak") as file:
for line in file:
print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='')
5. 标准输出重定向替换
import fileinput
with fileinput.input(files=('a.txt', 'data.txt'), inplace=False, backup='', mode='r', openhook=None) as f:
for line in f:
if fileinput.isfirstline():
print(fileinput.filename())
print(fileinput.fileno())
print(fileinput.filelineno(), line)
print(fileinput.lineno())
fileinput.close()
列举一些实用案例 案例三:利用 fileinput 将CRLF 文件转为LF
import sys
import fileinput
for line in fileinput.input(files=('a.txt', ), inplace=True):
if line[-2:] == "\r\n":
line = line + "\n"
sys.stdout.write(line)
案例四:配合 re 做日志分析:取所有含日期的行
aaa
1970-01-01 13:45:30 Error: **** Due to System Disk spacke not enough...
bbb
1970-01-02 10:20:30 Error: **** Due to System Out of Memory...
ccc
import re
import fileinput
import sys
pattern = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'
for line in fileinput.input('error.log',backup='.bak',inplace=1):
if re.search(pattern,line):
sys.stdout.write("=> ")
sys.stdout.write(line)
=> 1970-01-01 13:45:30 Error: **** Due to System Disk spacke not enough...
=> 1970-01-02 10:20:30 Error: **** Due to System Out of Memory...
案例五:利用fileinput实现类似于grep的功能
import sys
import re
import fileinput
pattern= re.compile(sys.argv[1])
for line in fileinput.input(sys.argv[2]):
if pattern.match(line):
print(fileinput.filename(), fileinput.filelineno(), line)
$ ./demo.py import.*re *.py
addressBook.py 2 import re
addressBook1.py 10 import re
addressBook2.py 18 import re
test.py 238 import re
linecache 模块
|