美文网首页
Python处理IO文件读写的相关demo

Python处理IO文件读写的相关demo

作者: jinhm007 | 来源:发表于2021-08-18 12:30 被阅读0次
'''
open()函数的第一个函数是要打开的文件名(文件区分大小写)
如果文件存在,返回文件操作对象
如果文件不存在,会弹出异常
read() 方法可以一次性 读入并返回文件的所有内容
close() 方阿飞负责关闭文件
 如果忘记关闭文件,会造成系统资源消耗,而且会影响后续对文件的访问
 注意:方法执行后,会把文件指针 移动到文件的末尾

在编写代码时,先处理打开和关闭,再处理里面的程序
'''
#demo1
# 1,打开一个文件注意大小写
file_str = open(r"C:\Users\Jhm\Desktop\test.xml")
file_target = open(r"C:\Users\Jhm\Desktop\test_copy.xml", "w")
# 2,读,写
while True:
    # 读取一行内容
    text = file_str.readline()
    # 判断是否读取到内容
    if not text:
        break
    file_target.write(text)
    print(text)
# 关闭
file_target.close()
file_str.close()

#demo2
# 打开文件
file_str = open(r"C:\Users\Jhm\Desktop\test.txt")
file_target = open(r"C:\Users\Jhm\Desktop\test2.txt", "w")

#读文件
def read(file_read):
    text = file_read.read()
    result = str(text)
    return result

#写文件
def write(con):
    lists = con.split(" ")
    print(lists)
    s = set()
    for name in lists:
        s.add(name)
    print(s)
    len2 = str(len(s))
    file_target.write(len2)
    print(len(s))

#调用方法
content = read(file_str)
write(content)
#关闭文件
file_str.close()
file_target.close()

#追加文件内容
file=open("b.txt","a")
file.write("\n hello world \n")
file.close()


#demo3
#拷贝图片

src_file=open(r"C:\Users\Jhm\Desktop\01.png","rb")
target_file=open(r"C:\Users\Jhm\Desktop\01_copy.png","wb")
target_file.write(src_file.read())
target_file.close()
src_file.close()

#通过with来处理
with open(r"C:\Users\Jhm\Desktop\01.png","rb") as src_file:
    with open(r"C:\Users\Jhm\Desktop\02_copy.png","wb") as target_file:
        target_file.write(src_file.read())


相关文章

  • Python处理IO文件读写的相关demo

  • python学习笔记03

    文件处理 读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。 读写文件前,我们先必须...

  • Python基础教程系列五:文件

    文件操作大纲 读写文件是最常见的IO操作。Python内置了读写文件的函数 1、文件操作 2、os 3、上下文处理器

  • 跟我一起学Python(八)

    一、IO编程 读写文件是最常见的IO操作,Python内置了读写文件的函数。文件读写的原理:在磁盘上读写文件的功能...

  • 用Python实现磁盘IO操作全攻略,让数据流动起来!

    01 文件读写 1. 打开文件 读写文件是最常见的IO操作。Python内置了读写文件的函数,方便了文件的IO操作...

  • 014.Python文件读写

    Python文件读写 1. 概述 读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。...

  • Python学习记录之:IO编程

    IO编程 文件读写 Python中文件读写语法和C兼容 读文件使用Python内置的open()函数,传入文件名和...

  • 31.Python:文件读写

    IO操作与读写文件 读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。不论哪种,一定...

  • Python读写文件

    Python 中读写文件是最为常见的磁盘IO操作,小伙伴们在使用 Python 处理数据时,有一部分数据是以文件的...

  • Python学习_IO文件操作

    在编程工作中,时常需要对各种文件进行操作。读写文件是最常见的IO编程,Python中内置了读写文件的函数。读写文件...

网友评论

      本文标题:Python处理IO文件读写的相关demo

      本文链接:https://www.haomeiwen.com/subject/dudgbltx.html