1.文件操作(IO技术)
(1)打开文件
f = open(文件名[,打开方式])
f = open('a.txt','a')
s = 'slene\nbai\n'
f.write(s)
f.close()
(2)编码
windows操作系统是GBK,python用Unicode编码
f = open('a.txt','w',encoding='UTF-8')
s = 'slene\nbai\n啦啦啦啦啦'
f.write(s)
f.close()
'''结果
slene
bai
啦啦啦啦啦
'''
(3)close()关闭文件流
s = 'baibaibai'
with open('a.txt','w') as f:
f.write(s)
try:
s = 'baibaibai'
f = open('b.txt','w')
f.write(s)
except BaseException as e:
print(e)
finally:
f.close()
(4)文本文件读取
with open('a.txt','r',encoding='gbk') as f:
print(f.read(5))
with open('a.txt','r',encoding='gbk') as f:
for a in f:
print(a,end='')
with open('a.txt','r',encoding='gbk') as f:
while True:
fragment = f.readline()
if not fragment:
break
else:
print(fragment,end='')
with open('a.txt','r') as f:
lines = f.readlines()
lines = [temp.rstrip() + '#'+str(index)+'\n' for index,temp in enumerate(lines)]
with open('a.txt','w') as f:
f.writelines(lines)
(5)二进制文件的读写
不加b,默认是文本文件
with open('D:\\photo\\Saved Pictures\\a.jpg','rb') as f:
with open('a.copy.jpg','bw') as w:
for line in f.readlines():
w.write(line)
print('finnish copy')
(6)文件对象常用的方法和属性
with open('b.txt','r') as f:
print('文件名是:{}'.format(f.name))
print('指针当前位置:',f.tell())
print('读取的一行内容:',str(f.readline()))
print('读完后指针现在的位置:',f.tell())
f.seek(7)
print('读取的一行内容:', str(f.readline()))
'''结果:
文件名是:b.txt
指针当前位置: 0
读取的一行内容: People may wonder why different words are used to describe these four countries:
读完后指针现在的位置: 82
读取的一行内容: may wonder why different words are used to describe these four countries:
'''
(7)使用pickle序列化
序列化指将对象转化成串行化数字形式
import pickle
a1 = 'bai'
a2 = 234
a3 = [20, 30, 40]
with open('data.dat','wb') as f:
pickle.dump(a1,f)
pickle.dump(a2,f)
pickle.dump(a3,f)
with open('data.dat','rb') as f:
b1 = pickle.load(f)
b2 = pickle.load(f)
b3 = pickle.load(f)
print(b1);print(b2);print(b3)
(8)csv文件的操作
import csv
with open('table1.csv','r') as f:
a_csv = csv.reader(f)
print(list(a_csv))
for row in a_csv:
print(row)
'''
[['id', 'name', 'age', 'salary'], ['1', 'bai', '18', '5000'], ['2', 'selene', '19', '8000'], ['3', 'tutu', '20', '10000']]
'''
import csv
with open('table1.csv','r') as f:
a_csv = csv.reader(f)
for row in a_csv:
print(row)
'''
['id', 'name', 'age', 'salary']
['1', 'bai', '18', '5000']
['2', 'selene', '19', '8000']
['3', 'tutu', '20', '10000']
'''
with open('table2.csv','w') as f:
b_csv = csv.writer(f)
b_csv.writerow(['id', '姓名', '年龄'])
b_csv.writerow(['01', '白', '24'])
b_csv.writerow(['02', '白2', '25'])
2.os和os.path模块
(1)os模块
import os
os.system(r'D:\\APP\\weixin\\WeChat\\WeChat.exe')
(2)文件和目录操作
import os
print(os.name)
print(os.sep)
print(repr(os.linesep))
print(os.stat('python148.py'))
print(os.getcwd())
os.mkdir('book')
os.chdir('d:')
os.mkdir('book1')
os.rmdir('book1')
os.makedirs('电影/美剧')
os.removedirs('电影/美剧')
os.makedirs('电影/美剧/老友记')
os.makedirs('../电影/韩剧/朴信惠')
dir = os.listdir('电影')
print(dir)
(3)os.path模块
import os
import os.path
print(os.path.isabs('D:/pytorch_learning'))
print(os.path.isdir('D:/pytorch_learning'))
print(os.path.isfile('D:/pytorch_learning'))
print(os.path.exists('D:/pytorch_learning'))
print(os.path.getsize('b.txt'))
print(os.path.abspath('b.txt'))
print(os.path.dirname('D:/pytorch_learning'))
print(os.path.getctime('b.txt'))
print(os.path.getatime('b.txt'))
print(os.path.getmtime('b.txt'))
path = os.path.abspath('b.txt')
print(os.path.split(path))
print(os.path.splitext(path))
print(os.path.join('d:\\','python','pytorch'))
import os
import os.path
work_dir = os.getcwd()
file_list = os.listdir(work_dir)
for filename in file_list:
if os.path.splitext(filename)[1] == '.py':
print(filename)
print('##########')
file_list2 = [filename for filename in os.listdir(work_dir) if filename.endswith('txt')]
for f in file_list2:
print(f,end='\n')
(4)walk()递归遍历所有文件和目录
import os
path = os.getcwd()
print(path)
file_list = os.walk(path)
for dirpath,dirnames,filenames in file_list:
for dir in dirpath:
print(dir)
(5)shutil拷贝
import shutil
shutil.copyfile('a.txt','a_copy.txt')
shutil.copytree('movie','movie2')
shutil.copytree('movie','movie3',ignore=shutil.ignore_patterns('*.txt','*.zip'))
(6)压缩
shutil.make_archive() zipfile
import shutil
import zipfile
shutil.make_archive('movie/gg','zip','movie/Korae')
z1 = zipfile.ZipFile('a.zip','w')
z1.write('a_copy.txt')
z1.write('a.copy.jpg')
z1.close()
z2 = zipfile.ZipFile('a.zip','r')
z2.extractall('movie2')
3.递归算法
def factorial(i):
global a
a = a * i
i = i-1
if i >1:
factorial(i)
else:
print(a)
factorial(int(input('input one number:')))
def factorial2(i):
if i == 1:
return i
else:
return i*factorial2(i-1)
print(factorial2(5))
import os
def getAllFiles(path):
childFiles = os.listdir(path)
for file in childFiles:
filepath = os.path.join(path,file)
if os.path.isdir(filepath):
getAllFiles(filepath)
print(filepath)
getAllFiles('movie')
'''结果
movie\a.txt
movie\America\bigbang
movie\America
movie\gg.zip
movie\Korae
'''
|