python-3.x - 在python中读取文件使用不同的方法
问题描述
# open file in read mode
f=open(text_file,'r')
# iterate over the file object
for line in f.read():
print(line)
# close the file
f.close()
文件内容为“恭喜您成功打开文件”!当我尝试运行此代码时,输出格式如下:
c (换行) o (换行) n (换行) g.......
......也就是说,每个字符都单独打印在新行上,因为我使用了 read()!但是使用 readline 它可以在一行中给出答案!为什么会这样?
解决方案
r.read()
返回一个字符串将所有字符(完整的文件内容)。
迭代一个字符串以字符方式迭代它。
利用
for line in f: # no read()
而是逐行迭代。
推荐阅读
- android - 从微调器中获取条件,并根据该条件从数据库中检索并列出列表视图中的数据
- microservices - 微服务和复制数据库表
- python - 如何使用 SQLAlchemy 的 `one_or_none` 查询方法?
- python - 如何在python中组合两个具有相同索引的系列?
- spring-boot - 在 Spring Boot 中使用无默认构造函数和最终字段进行 Bean 初始化
- java - 如何解析输入 JSON,并基于代表产品库存的现有 JSON 生成账单
- html - Buycraft ::从左边保持之前
- windows - Oracle 12c 安装问题
- python - 使用 python 2 和 smtplib 发送电子邮件时出错
- c++ - 将粒子投射到立方体的表面