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