python迭代文件内容

按字节处理:


f_name=open(path)
while c_str := f_name.read(1):
    print(f'read str is:{c_str}')
    c_str=f_name.read(1)
f_name.close()

可以使用while true/break语句结构进一步优化。优化代码如下

f_name=open(path)
while True:
    c_str=f_name.read(1)
    if not c_str:
        break
    print(f'read str is:{c_str}')
f_name.close()

按行处理:

f_name=open(path)
while True:
    line=f_name.readline(1)
    if not line:
        break
    print(f'read line is:{line}')
f_name.close()

用fileinput实现懒加载迭代
按行读取文件时,若能使用for循环,则称之为懒加载式迭代,因为在操作过程中只读取实际需要的文件部分。

 import fileinput
 
path='./test.txt'
for line in fileinput.input(path):
    print(f'line is:{line}') 

在该示例中没有看到文件的打开与关闭操作,是怎么处理文件的呢?其实这些操作被封装在input方法内部

os模块:
os.path.isfile(path):如果path是现有的常规文件,则返回TRUE。用来判断某一对象是否为文件(需传入绝对路径)
os.path.isdir(path):如果path是现有的目录,则返回TRUE。用来判断某一对象是否为目录(需传入绝对路径)

猜你喜欢

转载自blog.csdn.net/qq_41358574/article/details/114229755