python读文件逐行处理的示例代码分享
时间:2023-03-17 03:54:04
import os ## for os.path.isfile()
def dealline(line) :
print(line) ## 针对line我可以做很多事情
def getfilename() :
return input('Please input file name(input exit() for exit):').strip()
class more : ## MORE功能
linenum = 0
size = 10
def work(self) :
if self.linenum >= self.size :
if input('--MORE--').strip().lower() == 'exit()' :
return False
self.linenum = 0
else :
self.linenum += 1
return True
while True :
try :
filename = getfilename()
if filename.lower() == 'exit()' : ## 退出
break
if os.path.isfile(filename) : ## 判断文件是否存在
f = open(filename)
try :
lines = f.readlines()
m = more()
for line in lines:
if False == m.work() :
break
dealline(line)
## input()
finally :
f.close()
else :
print('File does not exists.')
##input()
except :
print('Input Error!')
还可以用
with open(filename) as fh:
for line in fh:
yield line
输出每一行
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python之pandas读写文件乱码的解决方法
javascript使用call调用微信API
Vue Socket.io源码解读
![](https://img.aspxhome.com/file/2023/4/123144_0s.png)
pytorch实现用Resnet提取特征并保存为txt文件的方法
python函数式编程学习之yield表达式形式详解
Prometheus的安装和配置教程详解
![](https://img.aspxhome.com/file/2023/0/117530_0s.png)
WinHTTP Services 5.1 参考资料
用户的期望以及背后真正的需求
Python常用内置模块之xml模块(详解)
![](https://img.aspxhome.com/file/2023/1/93641_0s.jpg)
python数据分析必会的Pandas技巧汇总
Python列表去重复项的N种方法(实例代码)
![](https://img.aspxhome.com/file/2023/0/60710_0s.jpg)
使用pyqt5 tablewidget 单元格设置正则表达式
![](https://img.aspxhome.com/file/2023/4/118544_0s.jpg)
Python命令行参数解析工具 docopt 安装和应用过程详解
在Python的Flask框架下使用sqlalchemy库的简单教程
动态载入树 (ASP+数据库)
echarts学习之legend点击事件解读
![](https://img.aspxhome.com/file/2023/4/132704_0s.png)
php中替换字符串函数strtr()和str_repalce()的用法与区别
Python深度学习神经网络残差块
![](https://img.aspxhome.com/file/2023/6/69616_0s.png)
基于Python实现RLE格式分割标注文件的格式转换
![](https://img.aspxhome.com/file/2023/5/87935_0s.png)
pygame实现贪吃蛇游戏
![](https://img.aspxhome.com/file/2023/2/115512_0s.jpg)