文件操作

  • 一、文件基础操作
    • 1. 基本读写操作
    • 2. 文件复制操作
  • 二、操作系统模块
    • 1.基础系统操作
    • 2.绝对路径和相对路径
  • 三、练习
    • 1. 拷贝联系
    • 2. 图书管理系统
  • 总结

**注意: 文中相关的路径和文件需要根据实际情况替换。**


一、文件基础操作

1. 基本读写操作

代码如下(示例):

"""
文件基本操作moder:读(纯文本)read(): 读取所有内容readline():每次读取一行内容readlines():读取所有的行保存的列表readable():判断是否有可读的w:写(纯文本)write()writelines():自己加换行注意:写操作write(s),每次都会清空原来的内容清空,写当前的内容rb:读二进制(图片、视频、音乐等)wb:写二进制()opr:open(path/fileName,mode='rt')   默认是gbk编码方式;decode       返回是流对象如果传递文件名有误,抛异常 FileNotFoundError"""
print("读文件".center(20, "*"))
# 读取文本stream = open(file=r'f:\test.txt', encoding='utf8')# line = stream.readline()
# print(line)  #
# content = stream.read()
# print(content)flag = stream.readable()
print(flag)# while True:
#     line = stream.readline()
#     print(line)
#     if not line:
#         breaklines = stream.readlines()
print(lines)
# 读取binary文件:图片
stream = open(file=r'f:\test.jpg', mode='rb')
pic = stream.read()
print(pic)
stream.close()print("写文件".center(20, "*"))stream = open(file=r'f:\test.txt', mode='w', encoding='utf8')
s = '''
统一代码管理统一代码管理 GitLib,是基于 Git 的代码管理平台,数十万企业正在使用,提供代码托管、代码评审、代码扫描、质量检测、持续集成等功能,全方位保护企业代码资产,帮助公司实现安全、稳定、高效的代码托管和研发管理。
统一开发工具”工欲善其事,必先利其器“,统一开发工具为流程中的每一步提效交付更迅捷
统一规范标准”车同轨,书同文“,统一规范标准为研发人员必须遵循的最低规范要求,无论什么产品,什么项目,都必须得严格遵守。
统一平台及技术栈统一平台及技术栈解决不统一带来的开发效率问题,系统维护成本显著增加,统一技术选型,降低团队学习成本;完善技术生态,技术方案提取和复用,提高开发效率。
统一组件库组件是对数据和方法的简单封装,随着开发与设计、策划、产品等岗位的密切协作,为了统一沟通语言,设计、产品等岗位也在广泛的使用组件这一概念。统一组件库可以提升工作能效和开发质量。
'''
result = stream.write(s)  # 返回写了几个字符
print(result)result = stream.write('hello world!')
result = stream.write(' 张三')
result = stream.writelines(["你好吗?\n", '一起去吃饭可以,有时间\n'])
print(result)
stream.close()print("写文件:不清空!".center(20, "*"))
stream = open(file=r'f:\test.txt', mode='a', encoding='utf8')result = stream.write("新增")
print(result)

2. 文件复制操作

代码如下(示例):

import os# 文件复制
"""原文件:F:\test.jpg目标文件:F:\test.jpgwith: 结合open使用,自动释放资源open:只能是文件os.path : 对系统中文件的操作os.path.dirname 获取文件夹os.path.join 拼接路径"""
print("复制文件".center(30, "*"))
with open(r"F:\test.jpg", 'rb') as r_stream:content = r_stream.read()abs_file_name = r_stream.nameprint(abs_file_name)start_index = abs_file_name.rfind("\\") + 1print(abs_file_name[start_index:])  # 截取文件名with open(r"F:\test1.jpg", 'wb') as w_stream:w_stream.write(content)print("文件复制完成!")print("批量复制文件".center(30, "*"))print(os.path)
path = os.path.dirname(__file__)
print(path)  # 当前文件的路径
print(type(path))new_path = os.path.join(path, "test.jpg")
print(new_path)print("复制文件到当前文件夹下".center(30, "*"))
with open(r"F:\test.jpg", 'rb') as r_stream:content = r_stream.read()new_path = os.path.join(os.path.dirname(__file__), "test.jpg")with open(new_path, 'wb') as w_stream:w_stream.write(content)
print("end-------------完成文件复制")

二、操作系统模块

1.基础系统操作

代码如下(示例):

#  os 模块
import os
import shutildir = os.getcwd()# 遍历
result = os.listdir(dir)  # 返回当前文件中的文件夹和文件,返回列表
print(result)# 创建目录
new_dir = os.path.join(dir, "copy_file")
print(new_dir)
if not os.path.exists(new_dir):  # 目录不存在,创建os.mkdir(new_dir)  # 创新新目录
if os.path.exists(new_dir):shutil.rmtree(new_dir)  # 删除shutil.copytree(dir, new_dir)
print('copy dir finished!')
# f = os.rmdir(new_dir)  # 只能删除空文件夹
# os.removedirs(new_dir)  # 删除多个目录
# print(f)print("清空文件夹,并删除目录".center(30, "*"))
# 遍历删除文件夹中文件和目录
new_result = os.listdir(new_dir)
for file in new_result:file_path = os.path.join(new_dir, file)os.remove(file_path)
else:os.rmdir(new_dir)  # 删除目录print("切换目录".center(30, "*"))f = os.chdir("../dictionary")
print(f)
print(os.getcwd())

2.绝对路径和相对路径

代码如下(示例):

# 文件路径操作
import os.path# 绝对路径
print(os.path.abspath(__file__))  # 获取绝对路径
print(os.path.isabs(__file__))  # 判断是否是绝对路径# 相对路径
os.path.isabs("/")
print(os.path.isabs("./test.jpg"))# 获取文件夹
path1 = os.path.dirname(__file__)  # 绝对路径,文件夹
path2 = os.path.abspath(__file__)  # 通过相对路径获取当前文件的绝对路径print(path1, path2)path3 = os.getcwd()  # 获取当前文件夹类似os.path.dirname(__file__)print(path3)# 获取文件路径
result = os.path.split(path2)  # 目录+ 文件名字
print(result)print(result[1])suf = os.path.splitext(path2)  # 获取扩展名
print(suf)size = os.path.getsize("test.jpg") #获取文件大小,单位是字节
print(size)

该处使用的url网络请求的数据。


三、练习

1. 拷贝联系

#  工具类#  copy
import os.pathdef copy(source, target):if not os.path.exists(target):os.mkdir(target)if os.path.isdir(source) and os.path.isdir(target):file_list = os.listdir(source)for file in file_list:path = os.path.join(source, file)with open(path, 'rb') as r_stream:content = r_stream.read()target_file = os.path.join(target, file)with open(target_file, 'wb') as w_stream:w_stream.write(content)else:print("拷贝完成!")# 调用函数
src = os.getcwd()
print(src)
tgt = os.path.join(src, "new_copy_file")
src = "E:\\workspace\\python\\demo-python\\dictionary"
print(tgt)
copy(src, tgt)

2. 图书管理系统

#  工具类#  copy
import os.pathdef copy(source, target):if not os.path.exists(target):os.mkdir(target)if os.path.isdir(source) and os.path.isdir(target):file_list = os.listdir(source)for file in file_list:path = os.path.join(source, file)with open(path, 'rb') as r_stream:content = r_stream.read()target_file = os.path.join(target, file)with open(target_file, 'wb') as w_stream:w_stream.write(content)else:print("拷贝完成!")# 调用函数
src = os.getcwd()
print(src)
tgt = os.path.join(src, "new_copy_file")
src = "E:\\workspace\\python\\demo-python\\dictionary"
print(tgt)
copy(src, tgt)
user_book.txt:sanduo:三国演义->水浒传
sanduo:鬼吹灯->倩女幽魂
sanduo:盗墓笔记->斗罗大陆
sanduo:鬼吹灯
sanduo:倩女幽魂
users.txt:sandduo 123456
sanduo 123
books.txt:斗罗大陆
斗破苍穹
三国演义
水浒传
诛仙
倩女幽魂
盗墓笔记
鬼吹灯

总结

这里对文章进行总结:

# 复习
"""
文件操作:open(path,mode)mode------>rs.read()s.readline()s.readlines()s.readable()with open('') as r_stram:passmode------>ws.write()s.writelines()s.writeable()with open('','w') as w_stram:w_stram.write('hello')os.path: os模块,常用函数os.path.abspath() 绝对路径os.path.dirname() 获取路径os.path.isabs() 判断是否是绝对路径os.path.getcwd() 获取文件夹os.path.join() 路径拼接os.path.split() 获取文件路径os.path.splitext() 扩展名os.path.getsize() 获取文件大小,单位是字节os.path.isfile()  是文件os.path.isdir() 是文件夹os 中的函数"""

Python3:文件操作相关推荐

  1. Python3 文件操作

    Python3 文件操作 讲师:张学亮 百度:学亮编程手记 网易云课堂:@张学亮 open() 方法 Python open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到 ...

  2. python从入门到大神---4、python3文件操作最最最最简单实例

    python从入门到大神---4.python3文件操作最最最最简单实例 一.总结 一句话总结: python文件操作真的很简单,直接在代码中调用文件操作的函数比如open().read(),无需引包 ...

  3. python输入文件名读取文件_[Python] python3 文件操作:从键盘输入、打开关闭文件、读取写入文件、重命名与删除文件等...

    1.从键盘输入 Python 2有两个内置的函数用于从标准输入读取数据,默认情况下来自键盘.这两个函数分别是:input()和raw_input(). Python 3中,不建议使用raw_input ...

  4. Python3文件操作详解 Python3文件操作大全

    1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author:sking 4 """ 5 test_file.tx ...

  5. python引用文件 mode写在后面还是前面,python3 文件操作常用mode参数用法详解

    python3:常用mode参数 t 文本模式 (默认). #假设我们有一个本地文件名为:demo.text,文件编码格式为:utf-8 #文件内容为:python工程狮 f = open('demo ...

  6. Python3文件操作:with...open的使用代码示例

  7. python3文件处理_简述 Python3 文件处理

    1.文件处理 找到文件 --> 打开文件 --> 操作:读.写 --> 保存 --> 关闭 1.1.1 写文件 (只要牵扯到文件操作,都是字符串:写文件的时候需要把写的数字转换 ...

  8. python3 转码的函数_python基础3之文件操作、字符编码解码、函数介绍

    内容概要: 一.文件操作 二.字符编码解码 三.函数介绍 一.文件操作 文件操作流程: 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 基本操作: 1 #/usr/bin/e ...

  9. python3 读取.plist文件_Python学习笔记 -5 - 文件操作

    Python文件操作 读写文件是最常见的IO操作,在磁盘上读写文件的功能都是由操作系统提供的,操作系统不允许普通的程序直接操作磁盘(大部分程序都需要间接的通过操作系统来完成对硬件的操作),所以,读写文 ...

  10. python3打开文件的代码_Python3 对文件操作

    计算机文件 在计算机系统中,以硬盘为载体存储在计算机上的信息集合称为文件.文件可以是文本文档.图片.声音.程序等多种类型.在编程时经常要对文件进行读写等操作, 从程序员的视角可以把文件理解为是连续的字 ...

最新文章

  1. 东财计算机应用基础在线作业答案,《计算机应用基础》东财在线20秋第一套作业答案...
  2. sprint计划会议
  3. 14、ORACLE下的基本SQL操作
  4. Spring –持久层–编写实体并配置Hibernate
  5. 【转】Dicom中的Image Orientation/Position的理解
  6. iphone 微信下浏览器中数字去除下划线
  7. Android Butterknife
  8. python程序文件的扩展名称是什么_python程序文件的扩展名称是什么_Python教程,python,扩展名...
  9. WebM (VP8) vs H.264
  10. 你对NLP的迁移学习爱的有多深?21个问题弄懂最新的NLP进展。
  11. spark常见问题定位
  12. Python中的时间序列数据可视化的完整指南
  13. 数字中国 · 青云科技:数字化转型过程中企业如何用好云计算?
  14. 学习之Java(方法)
  15. 喝干红葡萄酒的十大好处
  16. 云计算与大数据——云计算概述
  17. DTMF信号系统的Matlab仿真
  18. 提高网站排名的5大因素
  19. 打开新世界的大门——初识c语言
  20. Mux VLAN 原理

热门文章

  1. Linux Text file busy文本文件忙
  2. PropertyDescriptor
  3. 张维迎与马云舌战再起:怎么才是真正的企业家
  4. 我建议大学生看一下阿凡达2,对离校后很有帮助
  5. python汉明距离检索_汉明距离(Python3)
  6. WCD9335 audio driver Probe函数分析
  7. Clannad——让我了解友情,亲情和爱情的动画片
  8. Unity Shader 概述
  9. JAVA方面的书籍推荐
  10. 从键盘输入n个数 按从小到大的顺序排列输出