zoukankan      html  css  js  c++  java
  • 文件处理

    1、文件读写:

    file = open('file_name.txt','w',encoding='utf-8')
    names = ['a','b','c']
    n='wang,123'
    file.write(n)   #多用于字符串
    #file.writelines(n)
    for name in names:
        file.write(name)
    #for name in names:
    #    file.writelines(names)
    import time file = open('hahaha','w') file.write('kakaka') file.flush()   #立即把缓冲区里面的内容写到磁盘里面 with open('file_name.txt','w') as a , open('file_name2.txt') as a2: #打开多个文件 a.write('123') a2.write('456')

    2、以二进制模式打开图片:

    import requests
    url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1515746419895&di=9aa9a8429799de178ba0cc9cf06c89e9&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01a2e6567ce0bd6ac725ad903aa9bb.jpg'
    img = requests.get(url).content
    f = open('xiaohei.jpg','wb')  #bytes,以二进制模式打开
    f.write(img)

    3、修改文件两种方式:

    1/
    with open('nums', 'a+', encoding='utf-8') as f: f.seek(0) all = f.read() new_num = all.replace('1', '2') #a为旧字符串,b为新字符串 f.seek(0) f.truncate() f.write(new_num) f.flush()
    2/
    import os with open('nums',encoding='utf-8') as f, open('nums.gy','w',encoding='utf-8') as f2: for line in f: new_line = line.replace('1', '2') f2.write(new_line) os.remove('nums') #删文件 os.rename('nums.gy', 'nums') #改名
  • 相关阅读:
    MySQl数据约束练习
    MySQL查询实例
    网络通信协议简介(TCP与UDP)
    数据类型转换
    C++编译过的C代码为什么要用extern C
    hashtable
    以RB-tree为底层机制的几个关联式容器
    红黑树(RB-Tree)
    slist
    deque
  • 原文地址:https://www.cnblogs.com/wang-hao-yue/p/8275587.html
Copyright © 2011-2022 走看看