12月28日二周四次【Python基础语法】

2.6 使用for循环遍历文件
2.7 使用while循环遍历文件

2.6 使用for循环遍历文件

打开文件
  • open
    • r: 以只读方式打开
    • w: 以可写方式打开(文件不存在则创建,存在则覆盖内容)
    • a: 以追加模式打开,如果该文件不存在,创建新文件进行写入
    • r+: 打开一个文件用于读写
    • w+: 打开一个文件用于读写(参见W)
    • a+: 打开一个文件用于读写(参见a)
    • rb: 二进制读模式
    • wb: 二进制写模式(参见W)
    • ab: 二进制追加模式(参见a)
    • rb+: 以二进制格式打开一个文件用于读写(参见r+)
    • wb+: 以二进制格式打开一个文件用于读写(参见w+)
    • ab+: 以二进制格式打开一个文件用于读写(参见a+)
  • with open
    ## Win系统下打开文件
    print(open(r'D:\111.txt'))
    #####################################
    f = open(r'D:\1111.txt', 'w')       # 以w方式打开,没有则会创建
    f.write('sss')      # 写入(覆盖)的内容;只接受字符串
    f.close()           # 关闭打开的文件;不关闭则会占用内存
    #####################################
    ## 读文件内容
    f=open(r'D:\1111.txt','r').read()
    print(f)
    f.close() 
    #####################################
    f=open(r'D:\1111.txt','r').read(5)      # 读取5个字符
    print(f)
    f.close() 
    #####################################
    f=open(r'D:\1111.txt','r').readline()   # 以行来读内容
    print(f)
    f.close() 
    #####################################
    f=open(r'D:\1111.txt','r').readlines()  # 读取多行,返回list
    print(f)
    f.close() 
    #####################################
    ## 逐行遍历
    f=open(r'D:\1111.txt').readlines()
    for i in f:
    print("{}".format(i),end="")
    f.close() 
    #####################################
    ## 直接遍历;对内存开销小
    f=open(r'D:\1111.txt')
    for i in f:
    print("{}".format(i),end="")
    f.close() 

2.7 使用while循环遍历文件

## 遍历文件
f = open(r'D:\1111.txt')
while 1:
    line = f.readline()
    if not line:
        break
    print(line)
f.close()
##########################################
##  遍历文件
with open(r'D:\1111.txt') as f:       # with open 会自动关闭文件
    while 1:
        line = f.readline()
        if not line:
            break
        print(line)

习题

  • 1 . 现有一个文件test.txt ,内容如下:
    1234efgh
    abcd5678
    要求读出文件内容,对内容的顺序进行编辑,然后重新写入到文件,使其为如下形式
    12345678
    abcdefgh
    注意事项:使用pycharm的同学在调试程序时,如果程序对文件进行了操作,然后手动修改了文件,则要在pycharm中,程序所在的目录上点击右键,选择clean python compiled files,否则可能会报错
    l1 = []
    l2 = []
    with open(r'D:\test.txt') as f:
    while 1:
        line = f.readline()
        if line:
            for i in line:
                if i.isdigit():
                    l1.append(i)
                elif i != '\n':
                    l2.append(i)
        else:
            break
    l1.sort()
    l2.sort()
    with open(r'D:\test.txt','w') as f:
    for i in l1:
        f.write(i)
    else:
        f.write('\n')
    for i in l2:
        f.write(i)
    print("操作文成!")
  • 2 . 将上周五生成的dict3,排序后写入到文件dict.txt中,要求格式为
    A 65
    B 66
    C 67
    ...
    x 120
    y 121
    z 122
    
    import string
    s = 2
    dict1 = {'a': 97, 'c': 99, 'b': 98, 'e': 101, 'd': 100, 'g': 103, 'f': 102, 'i': 105, 'h': 104, 'k': 107, 'j': 106, 'm': 109, 'l': 108, 'o': 96, 'n': 110, 'q': 113, 'p': 112, 's': 115, 'r': 114, 'u': 117, 't': 116, 'w': 119, 'v': 118, 'y': 121, 'x': 120, 'z': 122}
    dict1['o'] = 111
    dict1 = sorted(dict1.items(), key=lambda a:a[0])
    dict1 = dict(dict1)
    dict2 = dict(zip(string.ascii_uppercase,range(65,92)))
    dict3 = dict(dict1, **dict2)
    dict3 = sorted(dict3.items(), key=lambda a:a[0])

with open(r'D:\dict.txt','w') as f:
for k,v in dict3:
f.write(k + ' ')
f.write(str(v) + '\n')

转载于:https://blog.51cto.com/13542406/2055655

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值