Python - jupyter

若不存在文件夹则创建对应文件夹

1
2
3
4
5
import os
path = waveletG
err = 0.1
if not os.path.exists('./{}/wavenumber{}'.format(path[0:-1],err)):
os.makedirs('./{}/wavenumber{}'.format(path,err))

循环内定义文件名称

1
filename ='{}/{}'.format(path,file)

按列读取文件数据

1
2
3
4
5
6
7
8
X0,X1= [],[]
with open(filename, 'r',) as f:
next(f) #跳过第一行
lines = f.readlines()
for line in lines:
value = [float(s) for s in line.split()]
X0.append(value[0]) # 第一列
X1.append(value[1]) # 第二列

输出到txt文件的列间距控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
filename = 'N=3-R_10={:3.2f}mm-R_20={:3.2f}mm-{:4.1f}MPa.txt'.format(R_10*1e3,R_20*1e3,pin0/1e6)

#标题
with open(filename, 'w') as f:#创建空白文档
Tittle = 'T(ms)','R_1(mm)','U_1(m/s)','DU_1(m/s^2)'
print("{:<10}{:<10}{:<10}{:<16}".format(*Tittle), file=f)#居左
f.close()
#数据
with open(filename, 'a') as f:#写入
if i % 1000 == 0:
print("{:<9.3f}".format(t*1e3),
"{:<9.3f}".format(R_1*1e3),
"{:<9.3f}".format(U_1),
"{:<15.3f}".format(DU_1),
file=f)
f.close()

注意到标题为str,写入位数要比数据多一位。