Python学习笔记13——文件(自用不全)

1、

file = open('a.txt','r')    #r表示读取的意思
print(file.readlines())     #readlines结果是一个列表,会读取文件的所有内容
file.close()

输出结果:
[‘中国\n’, ‘美丽’]

2、

file = open('b.txt','w')    #w表示写入的意思
file.write("python")   #在磁盘中没有的文件,会进行创建
file.close()

3、

file = open('b.txt','a')    #a会在原有内容下进行追加
file.write("python")
file.close()

4、

src_file = open('logo.png','rb')

target_file = open('copylogo.png','wb')

target_file.write(src_file.read())

target_file.close()
src_file.close()

5、+ 以读写方式打开文件,不能单独使用,需要与其他模式一起使用,如a+

6、

file = open('a.txt','r')
print(file.read())
file.close()

输出结果:
中国
美丽

file = open('a.txt','r')
print(file.read(2))   #会只读取中国两个字
file.close()

输出结果:
中国

file = open('a.txt','r')
print(file.readline())   #只读一行,中国
file.close()

输出结果:
中国

file = open('a.txt','r')
print(file.readlines())    #输出列表
file.close()

输出结果:
[‘中国\n’, ‘美丽’]

7、

file = open('c.txt','a')
#file.write('hello')
lst = ['java','go','python']
file.writelines(lst)
file.close()

在c.txt中的输出结果:
javagopython

8、

file = open('a.txt','r')
file.seek(2)      #一个中文2个字节
print(file.read())
print(file.tell())
file.close()

输出结果:

美丽
10

9、

file = open('d.txt','a')
file.write('hello')
file.flush()
file.write('world')
file.close()

#close在flush之后时是可以写入的
file = open('d.txt','a')
file.write('hello')
file.close()
# file.write('world')
# file.flush()

#flush在close之后会报错

10、

with open('a.txt','r') as file:
    print(file.read())
#用with就不用每次都要关闭了,当离开with语句时,它会自动释放资源

输出结果:
中国
美丽

11、
os模块是与操作系统相关的一个模块

#os模块是与操作系统相关的一个模块
import os
# os.system('notepad.exe')   #打开记事本
# os.system('calc.exe')   #打开计算器

#直接调用可执行文件
#os.startfile('D:\\qq\\Bin\\qq.exe')

print(os.getcwd())

输出结果:
D:\00python\learnwork\part13

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值