• 第三章 文件操作


    文件操作分为 读 写 修改 

    示例:

    f =open(file='db.txt',mode='r',encoding='utf-8')   r 只读 r+ 读写 w+ 写读 w 写  rb  以二进制方式读取  a 把内容追加到文件尾部

    data=f.read()

    f.close()

    循环文件

    f = open(file='db.txt','r',encoding="utf-8")

    for line in f :

        print (line)

    f.close()

    写文件

    f = open(file='db.txt','w',encoding="utf-8")

    f.write('aslkfladfasdf')

    f.close()

    占硬盘方式的文件修改代码示例

    模拟登陆

    import os

    f = oopen(f_name,'r',encoding='utf-8')

    f_new=open(f_new_name,'w',encoding='utf-8')

    for line in f:

        if old_str in line:

            new_line = line.replace(old_str,new_str)

        else:

            new_line = line

        f_new.write(new_line)

    f.close()

    f_new.close()

    os.rename(f_new_name,f_name)

    while True:

    name=input('请输入用户名>>:  ')

    with open ('lock.txt','r',encoding='utf-8') as read_f:

     f=read_f.read()

    if name in f:

        print('次用户已锁定‘)

    break 

    psw=input('请输入密码>>: ')

    with open ('user.txt','r',encoding='utf-8') as read_f:

    for line in read_f:

        l=line.strip().split(',')

       if name==l[0] and psw==l[1]:

        print(‘登陆成功’’)

        break

        else:

       

           print('请重新输入')

         count+=1

      if count=3 :

     with open ('lock.txt','w',encoding='utf-8') as write_f:

        write_f.write(name)

        print('用户已锁定')

        break

    全局替换

    import sys
    import os
    count=0 if len(sys.argv) != 3: print('usage: cp source_file target_file') sys.exit()
    old_str,new_str=sys.argv[1],sys.argv[2] 
    with open(f_new_name,'rb') as f,open(f_new_name,'wb') as f_new:
    for line in f:
    if old_str in line:
    new_line=line.replace(old_str,new_str)
    count+=1
    else:
    new)line=line
    f_new.write(new_line)
    os.rename(f_new_name,f_name)
    print('count')
  • 相关阅读:
    [转]jquery开发自定义的插件总结
    [转]net中哈希表的使用 Hashtable
    [转]C#编程总结(三)线程同步
    [转]大白话系列之C#委托与事件讲解(三)
    [书目20160706]成功销售实用经典10步骤(美国培训与发展协会实用经典10步系列)
    [转]backbone.js template()函数
    [转]ASP.NET MVC Dynamic Themes
    [转]C#网络编程(订立协议和发送文件)
    [转]C#网络编程(异步传输字符串)
    [转]C#网络编程(同步传输字符串)
  • 原文地址:https://www.cnblogs.com/mayicai/p/8964114.html
Copyright © 2020-2023  润新知