准备工作:os常用命令 自建一个文件夹,将当前目录修改为当前文件夹
import os
os.chdir(“D:\4.23”)
os.getcwd()
‘D:\4.23’
os.mkdir(“file_1”) #在当前目录建立子文件夹
os.mkdir(“file_2”)
os.rmdir(“file_2”) #删除文件夹
open(“my_file.txt”,‘w’) #w是只写,r是只读
<_io.TextIOWrapper name=‘my_file.txt’ mode=‘w’ encoding=‘cp936’>
open(“my_file_1.doc”,‘w’)
<_io.TextIOWrapper name=‘my_file_1.doc’ mode=‘w’ encoding=‘cp936’>
open(“hahaha.py”,‘w’)
<_io.TextIOWrapper name=‘hahaha.py’ mode=‘w’ encoding=‘cp936’>
查看该路径下的文件和文件夹
os.listdir()
[‘file_1’, ‘my_file.txt’, ‘my_file_1.doc’]
os.rename(“a.txt”,“b.py”) #改名
import os
os.chdir(“D:\4.23”)
os.mkdir(“big_data”)
FileExistsError Traceback (most recent call last)
in ()
----> 1 os.mkdir(“big_data”)
FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: ‘big_data’
os.chdir(“D:\4.23\big_data”)
open(“a.txt”,‘w’)
<_io.TextIOWrapper name=‘a.txt’ mode=‘w’ encoding=‘cp936’>
open(“b.doc”,‘w’)
<_io.TextIOWrapper name=‘b.doc’ mode=‘w’ encoding=‘cp936’>
open(“c.py”,‘w’)
<_io.TextIOWrapper name=‘c.py’ mode=‘w’ encoding=‘cp936’>
import os
for i in os.listdir():
os.rename(i,‘great_’+i)
for i in os.listdir():
os.rename(i,i - ‘great_’)
TypeError Traceback (most recent call last)
in ()
1 for i in os.listdir():
----> 2 os.rename(i,i - ‘great_’)
TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’
文件的打开与关闭
open(“my_file.txt”,‘w’).close()
open(“my_file_1.doc”,‘w’).close()
open(“hahaha.py”,‘w’).close()
‘r’ 只读
‘w’ 只写
‘x’ 创建写,文明不存在则创建,存在则返回异常
‘a’ 追加写模式,文件不存在则创建,存在则在原文件最后追加内容
‘b’ 二进制文件模式
‘t’ 文本文件模式,默认值
‘+’ 与r/w/x/a一同使用,在原功能基础上增加同时读写功能
f = open(‘a.txt’,‘x’)
f.close() #关闭文件
f=open(‘a.txt’,‘w’)
f.write(“Hello world!”)
12
f = open(‘a.txt’,‘r’)
f.read()
‘Hello world!’
f.seek(0) #自定光标的位置
0
f.tell() #返回光标的位置
0
f.read(3)
‘Hel’
f.close()
help(open)