首页 > 解决方案 > 在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 它可以在一行中给出答案!为什么会这样?

标签: python-3.xfile

解决方案


r.read()返回一个字符串将所有字符(完整的文件内容)。

迭代一个字符串以字符方式迭代它。

利用

for line in f:   # no read()

而是逐行迭代。


推荐阅读