在预处理文件以及训练模式时经常用到一个文件操作,这里稍加整理。

os

1
2
import os
import shutil

OS 操作很常用,用于获取文件夹之类的操作。主要使用osshutil两个库文件。

基本函数

1
2
3
4
os.path.exists(path)
os.path.isdir(path)
os.path.isfile(path)
files = os.listdir(path)

判断路径是否存在,是一个文件夹还是一个文件。对于一个文件夹可以继续使用 listdir 获得文件内容

创建文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def mkdir(path):

path=path.strip()
path=path.rstrip("\\")

isExists=os.path.exists(path)

if not isExists:
os.makedirs(path)
print('OK!')
return True
else:
print('Existed!)
return False

删除文件夹

1
2
3
os.remove(path)
os.rmdir(path) #仅能删除空文件夹
shutil.rmtree(path) #递归删除所有内容

重命名

对于文件夹和文件的操作方法是一样的。

1
2
os.rename("test","test1")    
os.rename("test.txt","test1.txt")

复制和移动

需要使用 shutil 的库文件操作。

1
2
3
4
shutil.copyfile("foo.txt","bar.txt")  # file only
shutil.copytree("foo","bar") # dir only
shutil.copy("foo","bar") # both
shutil.move("foo","bar")
  • 上述的文件的复制方法,存在覆盖能力。文件夹的复制方法则不允许在目标地址存在相应文件夹。
  • 如果调用.copy(),输入为一个文件和一个文件夹,则会将文件复制入文件夹中。
  • .move()细节和.copy()相同

文件读写操作

基本读写

1
2
3
4
5
6
with open(path, 'w', encoding = "utf-8") as f:
f.write('foobar!')
with open(path, 'r', encoding = "utf-8") as f:
lines = f.readlines()
for line in lines:
pass

模式:

参数 效果
w 写文件
r 读文件
a 追加文件

特殊:json

JSON 文件是常用的格式,为了方便存储字典型结构的最优选择。

1
2
3
4
5
import json
with open('dataset.json', 'r') as f:
data = json.load(f)
with open('dataset.json', 'w') as f:
json.dump(dataset, f)

特殊:pickle

pickle 常用来保存二进制数据结构。基本上是什么都能存。不过对于 PyTorch,还是建议使用 torch 自带的 save 函数,不然 torch 会报 warning。

1
2
3
4
5
import pickle as pk
with open('dataset.pk', 'wb') as f:
pk.dump(data, f)
with open('dataset.pk', 'rb') as f:
data = pk.load(f)