Python经常忘记的操作:文件和文件夹操作 嵌套语句
1、文件操作
参考链接:Python 3 菜鸟教程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| for tmpdir in [mask_dir, viz_dir]: if not os.path.exists(tmpdir): os.mkdir(tmpdir)
(file, ext) = os.path.splitext(url) (path, filename) = os.path.split(url)
os.path.abspath(__file__) os.path.realpath(__file__)
shutil.copy(LAST, BEST)
names = os.listdir(project_path)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| read() readline() readlines()
file1 = open("test.txt") file2 = open("output.txt","w") while True: line = file1.readline() file2.write('"'+line[:s]+'"'+",") if not line: break file1.close() file2.close()
file2 = open("output.txt","w") for line in open("test.txt"): file2.write('"'+line[:s]+'"'+",") file2.close()
with open('somefile.txt', 'r') as f: data = f.read()
with open('somefile.txt', 'r') as f: for line in f:
with open('somefile.txt', 'w') as f: f.write(text1)
with open('somefile.txt', 'w') as f: print(line1, file=f) print(line2, file=f)
|
2、Numpy / PyTorch
转换
1 2 3 4 5
| tor_arr = torch.from_numpy(np_arr) np_arr = tor_arr.numpy()
np_arr = cuda_arr.cpu().detach().numpy()
|
Numpy
1 2 3 4 5 6 7 8 9 10
| np.random.random np.random.rand np.random.randint np.random.randn np.random.normal np.random.uniform np.random.seed np.random.shuffle np.random.choice
|
1 2 3 4 5 6 7 8
| a*b
a.dot(b) np.dot(a, b)
np.linalg.inv(a) np.matrix().I
|
1 2 3 4 5 6 7 8 9 10 11 12
| ```
* GPU
```python
os.environ["CUDA_VISIBLE_DEVICES"] = '0,1,2,3'
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| ```
* 单应性估计和变换
```python
cv2.getPerspectiveTransform(pts2, pts1) cv2.findHomography()
cv2.warpPerspective()
|
1 2
| cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]])
|
1 2 3 4 5
|
cv2.putText(src, text, place, Font, Font_Size, Font_Color, Font_Overstriking) img_1 = cv2.putText(img_1, 'image 1', (10,height-10), cv2.FONT_HERSHEY_COMPLEX, 1.0, (100, 200, 200), 1)
|
1 2 3 4 5 6 7 8
| kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3, 3)) cv2.erode(mask, kernel) cv2.dilate(mask, kernel)
cv2.morphologyEX(mask, cv2.MORPH_CLOSE, kernel)
|
4、基础操作
1 2 3 4
| "cwd": "${fileDirname}"
|