while和for循环&读取大文件&三种读取文件方式

目录

While和for循环

for循环实现猜三次年纪

age = 66
count = 0
for i in range(3):
    guess_age = int(input('age:'))
    if guess_age == age:
        print("right")
        break
    elif guess_age < age:
        print("too small")
    else:
        print("too large")
else:
    print("you have tried too many times")

while循环

作用:一般来说循环会一直执行到条件为假,或到序列元素用完时,但是有些时候会提前终止一些循环

  • break : 直接跳出循环
  • continue:跳出本次循环进行下一次循环

while循环实现猜三次年纪

age = 66
count = 0
while count < 3:
    guess_age = int(input('age:'))
    if guess_age == age:
        print("right")
        break
    elif guess_age < age:
        print("too small")
    else:
        print("too large")
    count += 1
else:
    print("you have tried too many times")

读写文件

open函数用来打开文件

open(name[, mode[, buffering]]) 打开文件可传的参数

  • open函数使用一个文件名作为唯一的强制参数,然后返回一个文件对象。
  • 模式(mode)和缓冲(buffering)参数都是可选的

打开文件的模式有

• r,只读模式(默认)。
• w,只写模式。【不可读;不存在则创建;存在则删除内容;】
• a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
注:  "+" 表示可以同时读写某个文件
• w,只写模式。【不可读;不存在则创建;存在则删除内容;】
• w+,写读
• a+,同a

with语句

作用:将打开文件写在with中当对文件操作完成后with语句会自动帮关闭文件,避免忘记写f.close()
 
with读文件

with open("data1.txt",'r',encoding = 'utf-8') as f:
    for line in f:
        print(line)

三种读操作比较

  • read(): 指定读取指定大小的文件(默认一次读取所有)
  • readline(): 逐行读取,适合读大文件
  • readlines(): 一次性读取所有文件, 将文件按行读取成列表

三种读操作举例说明

#1. read()一次读取所有内容
'''aaa111
bbb222'''
f = open(r"data.txt")
print(f.read())
f.close()

#2. readline(),每次只读取一行,光标下移
'''
0: aaa111

1: bbb222
'''
f = open(r"data.txt")
for i in range(2):
    print(str(i) + ": " + f.readline(),)

#3. 一次读取所有,每行作为列表的一个值
'''['aaa111\n', 'bbb222\n']'''
f = open(r"data.txt")
print(f.readlines())

我们使用了一个 while 循环来读取文件内容,每次最多读取 8kb 大小

这样可以避免之前需要拼接一个巨大字符串的过程,把内存占用降低非常多。

python读写大文件

#!/usr/bin/python
# -*- coding: utf-8 -*-
def read_big_file_v(fname):
    block_size = 1024 * 8
    with open(fname,encoding="utf8") as fp:
        while True:
            chunk = fp.read(block_size)
            # 当文件没有更多内容时,read 调用将会返回空字符串 ''
            if not chunk:
                break
            print(chunk)
path = r'C:\aaa\luting\edc-backend\tttt.py'
read_big_file_v(path)

read()读文件

  • read(n)读取指定长度的文件

read读取指定长度字符串

f = open(r"somefile.txt")
print(f.read(7))        # Welcome        先读出 7 个字符
print(f.read(4))        #‘ to ‘                接着上次读出 4 个字符
f.close()
  • seek(offset[, whence]) 随机访问
    作用:从文件指定位置读取或写入

从指定位置写入

f = open(r"somefile.txt", "w")
f.write("01234567890123456789")
f.seek(5)
f.write("Hello, World!")
f.close()
f = open(r"somefile.txt")
print(f.read())                 # 01234Hello, World!89
  • tell 返回当前读取到文件的位置下标

返回读取位置下标

f = open(r"somefile.txt")
f.read(1)
f.read(2)
print(f.tell())             # 3     3就是读取到文件的第三个字符

readline()读文件

作用:readline 的用法,速度是fileinput的3倍左右,每秒3-4万行,好处是 一行行读 ,不占内存,适合处理比较大的文件,比如超过内存大小的文件

readline读取大文件

f1 = open('test02.py','r')
f2 = open('test.txt','w')
while True:
    line = f1.readline()
    if not line:
        break
    f2.write(line)
f1.close()
f2.close()

readlines()读文件

作用:readlines会把文件都读入内存,速度大大增加,但是木有这么大内存,那就只能乖乖的用readline

f1=open("readline.txt","r")
for line in f1.readlines():
    print(line)

参考链接来自于此

发布了75 篇原创文章 · 获赞 62 · 访问量 4660

猜你喜欢

转载自blog.csdn.net/weixin_45139342/article/details/104781345