1 文件与IO

1.1读写文本数据

读写各种不同的文本数据,如ASCII,UTF-8,UTF-9编码等。

使用带有rt模式的open()函数读取文本文件。

例如:
with open('db', 'rt') as f:
data = f.read()
print(data)
with open('db', 'rt') as f:
for line in f:
print(line.strip('\n'))

使用带有wt的open()函数写入一个文本文件,如果之前文件内容存在则清除并覆盖掉。

例如:
with open('db', 'wt') as f:
f.write('python|python235')

如果是已存在文件中添加内容,使用at的open()函数。

操作文件时指定默认编码

with open('somefile.txt', 'rt', encoding='latin-1') as f:
... 

注意:

当使用with语句时,不需要手动关闭文件,当with控制块结束时,文件会自动关闭。不用with时,需要手动关闭。

1.2文件不存在时写入

在一个文件中写入数据,如果文件不存在写入,而不是直接覆盖原文件内容。

例如:
with open('db', 'xt') as f:
f.write('hello')
db文件存在抛出FileExistsError异常
Traceback (most recent call last):
File "C:/Users/hexm/Desktop/python/s13/day3/file01.py", line 9, in <module>
with open('db', 'xt') as f:
FileExistsError: [Errno 17] File exists: 'db' 替代方案:
import os
if not os.path.exists('db'):
with open('db', 'wt') as f:
f.write('hello\n')
else:
print('File already exists')

1.3读写二进制文件

例如:
f = open('db', 'rb')
res = f.read()
print(res, type(res)) #b'ssssssssss' <class 'bytes'>
text = res.decode('utf-8')
print(text) f = open('db', 'ab')
text = 'hello,世界'
f.write(bytes(text, encoding='utf-8'))
f.write(text.encode('utf-8')) f = open('db', 'ab')
f.write(b'Hello world.')

1.4 打印输出到文本文件

打印输出至文件中,将print()函数输出重定向到一个文件中。

例如:
with open('db', 'wt') as f:
print('python1|python279', file=f)

1.5 使用其他分隔符或行终止符打印

可以在print()函数中使用sep和end关键字。

例如:
print('xiaoming', 2, 3, 5)
print('xiaoming', 2, 3, 5, sep=',', end='!!!\n')
for x in range(10):
print(x, end=' ') #0 1 2 3 4 5 6 7 8 9

使用str.join()也可以做到,不过str.join()仅使用于字符串。

例如:
print(','.join(str(x)for x in name)) #xiaoming,2,3,5
print(*name, sep = ',') #xiaoming,2,3,5

1.6 format格式化输出

#format格式化输出
s1 = 'I am {0}, age {1}'.format('hexm', 18)
print(s1) #I am hexm, age 18
s2 = 'I am {0}, age {1}'.format(*['hexm', 18])
print(s2) #I am hexm, age 18
s3 = 'I am {name}, age {age}'.format(name='hexm', age=18)
print(s3) #I am hexm, age 18
s4 = 'I am {name}, age {age}'.format(**{'name': 'hexm', 'age': 18})
print(s4) #I am hexm, age 18
监控文件尾部,并打印
#!/usr/bin/env python
# coding=utf-8 import time def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line if __name__ == '__main__':
logfile = open('/tmp/access.log', 'r')
loglines = follow(logfile)
for line in loglines:
print(line.strip())
监控文件尾部,并打印,退出后从退出位置监控
#!/usr/bin/env python
# coding=utf-8
import time
import os
def follow(seek_bytes, file):
seek_bytes = int(seek_bytes)
file.seek(seek_bytes) # 跳到位置信息
while True:
line = file.readline()
if not line:
time.sleep(0.1)
continue
else:
# 保存位置信息
with open('/tmp/linenumber.log', 'w+') as f:
f.write(str(file.tell()))
yield line
if __name__ == '__main__':
logfile = open('/tmp/access.log', 'r')
# 如果位置文件存在,打开并读取
if os.path.exists('/tmp/seek_bytes.log'):
with open('/tmp/seek_bytes.log', 'r') as f:
seek_bytes = f.readline().strip()
# 位置设置为0
else:
seek_bytes = ''
# 将位置信息和文件对象传给follow函数
loglines = follow(seek_bytes, logfile)
for line in loglines:
print(line.strip())
												

python文件操作及格式化输出的更多相关文章

  1. Python基础篇【第2篇】: Python文件操作

    Python文件操作 在Python中一个文件,就是一个操作对象,通过不同属性即可对文件进行各种操作.Python中提供了许多的内置函数和方法能够对文件进行基本操作. Python对文件的操作概括来说 ...

  2. 初学Python——文件操作第二篇

    前言:为什么需要第二篇文件操作?因为第一篇的知识根本不足以支撑基本的需求.下面来一一分析. 一.Python文件操作的特点 首先来类比一下,作为高级编程语言的始祖,C语言如何对文件进行操作? 字符(串 ...

  3. Python之路Python文件操作

    Python之路Python文件操作 一.文件的操作 文件句柄 = open('文件路径+文件名', '模式') 例子 f = open("test.txt","r&qu ...

  4. Python文件操作:文件的打开关闭读取写入

    Python文件操作:文件的打开关闭读取写入 一.文件的打开关闭 Python能以文本和二进制两种方式处理文件,本文主要讨论在Python3中文本文件的操作. 文件操作都分为以下几个步骤: 1.打开文 ...

  5. [Python学习笔记][第七章Python文件操作]

    2016/1/30学习内容 第七章 Python文件操作 文本文件 文本文件存储的是常规字符串,通常每行以换行符'\n'结尾. 二进制文件 二进制文件把对象内容以字节串(bytes)进行存储,无法用笔 ...

  6. Python小代码_2_格式化输出

    Python小代码_2_格式化输出 name = input("name:") age = input("age:") job = input("jo ...

  7. Python文件操作与函数目录

    文件操作 python文件操作 函数 Python函数学习——初步认识 Python函数学习——作用域与嵌套函数 Python函数学习——匿名函数 python内置函数 Python函数学习——递归 ...

  8. day8.python文件操作

    打开和关闭文件 open函数 用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写. file = open(file_name [, access_ ...

  9. 关于python 文件操作os.fdopen(), os.close(), tempfile.mkstemp()

    嗯.最近在弄的东西也跟这个有关系,由于c基础渣渣.现在基本上都忘记得差不多的情况下,是需要花点功夫才能弄明白. 每个语言都有相关的文件操作. 今天在flask 的例子里看到这样一句话.拉开了文件操作折 ...

随机推荐

  1. JS基础(一)异常错误

    EvalError(运算错误): raised when an error occurs executing code in eval() RangeError(范围错误): raised when ...

  2. 【Leetcode】378. Kth Smallest Element in a Sorted Matrix

    Question: Given a n x n matrix where each of the rows and columns are sorted in ascending order, fin ...

  3. Docker 下 mysql 简单的 主从复制实现

    1. 拉取镜像 docker pull mysql: 2. 运行这个镜像 docker run -d --name maser mysql: 3. 安装一些必要的软件 docker exec -it ...

  4. MacBook Pro 电池寿命

    MacBook Pro 电池寿命 https://www.apple.com/cn/macbook-pro/specs/ https://www.zhihu.com/question/19709979 ...

  5. apache 运行一段时间出现错误

    环境是win2008,apache 2.4.29 Win64 VC15,php 7.1.10(7.1.11).事件完整内容: “-------------------------- 错误应用程序名称: ...

  6. 神奇的Redis延迟

    最近在做某业务Redis的缩容工作,涉及到数据迁移,而Redis的数据迁移看起来蛮简单的,一对一的数据迁移只需要在slave行配置masterauth 和slaveof 两个参数即可,当然迁移过程中涉 ...

  7. 洛谷SP16580 QTREE7 - Query on a tree VII(LCT,multiset)

    洛谷题目传送门 思路分析 维护子树最值还是第一次写QwQ 因为子树的最值会变化,所以不能简单地把最值记下来,还要维护一个平衡树,把每个子树的最大值扔进去,来资磁插入.删除和查询最值. 然后我就懒得手写 ...

  8. 沉迷AC自动机无法自拔之:[UVA 11468] Substring

    图片加载可能有点慢,请跳过题面先看题解,谢谢 这个鬼题目,上一波套路好了 先用题目给的模板串建\(AC\)自动机,把单词结尾标记为 \(val=1\),然后在建好的\(AC\)自动机上跑 \(dp\) ...

  9. 【BZOJ2178】圆的面积并(辛普森积分)

    [BZOJ2178]圆的面积并(辛普森积分) 题面 BZOJ 权限题 题解 把\(f(x)\)设为\(x\)和所有圆交的线段的并的和. 然后直接上自适应辛普森积分. 我精度死活一个点过不去,不要在意我 ...

  10. 解题:国家集训队 Middle

    题面 求中位数的套路:二分,大于等于的设为1,小于的设为-1 于是可以从小到大排序后依次加入可持久化线段树,这样每次只会变化一个位置 那左右端点是区间怎么办? 先把中间的算上,然后维护每个区间左右两侧 ...