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') #改名
  • 相关阅读:
    加载图片出现403的问题
    js字符串首字母大写的不同写法
    vue中使用两个window.onresize问题解决
    vue备用
    vue注册全局组件
    Java中Timer的用法
    笔记本设置wifi热点
    UVA 11401 Triangle Counting
    数论专题---除法表达式之高精度运算,扩展欧几里得算法
    能被2、3、4、5、6、7、8、9整除数的特征
  • 原文地址:https://www.cnblogs.com/wang-hao-yue/p/8275587.html
Copyright © 2011-2022 走看看