2023.4.12 python学习记录(操作文件内容以及os模块)

#1.读取文件磁盘的内容
file = open('1.txt','r')
print(file.read())    #从头读到尾
print(file.readline())   #读取一行
print(file.readlines())   #将文本每一行作为一个独立的字符串,放入列表
file.close()

#2.常用的文件打开形式
file = open('2.txt','w')   #替换文件内容
file.write('hello wangyuan')
file = open('2.txt','a')    #对文件内容进行追加
file.write('hello wangyuan')
lst = ['java','go','python']
file.writelines(lst)   #写入列表的内容
file.seek(2)   #对字符进行跳过,跳过两个字符位
file.close()
src_file = open('cat.jpg','rb')   #以二进制方式进行读取
target_file = open('cat2.jpg','wb')
target_file.write(src_file.read())   #复制图片完成读写操作
target_file.close()
src_file.close()

#3.with 上下文管理器
with open('1.txt','r') as ffile:
    print(ffile.read())

#4.os模块,与操作系统相关的文件
import os
os.system('notepad.exe')   #与windos+r效果相同,打开记事本
os.system('calc.exe')   #打开计算器
os.startfile(r'"C:\Program Files (x86)\Tencent\QQ\Bin\QQScLauncher.exe"')  #执行可执行文件
os.path.join(r'D:\pythonProject','1.txt')   #对对应路径进行拼接
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值