python中utils

python使用过程中,会有很多需求,但是真的是很小很小的需求,就稍稍整理放在这里,不断记录。

场景1:文件不重复命名,文件读写
关键词:time:

import time
localTime = time.strftime("%Y%m%d%H%M%S",time.localtime()) 

filename = localTime + '.txt' # 20171220141801.txt
fout = open(filename, 'w')
fout.write('你好啊')
fout.close()

利用time的特殊性控制生成每次都不同的字符串

场景2: 将numpy和list内容保存到txt中
关键词:

# numpy=>txt
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6]])
np.savetxt('data.txt', data) # 如果data中存在字符串(非数字),则无法保存
"""
1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00
"""

# list=>txt
fout=open('data.txt','w')  
list_data = [[1, 2, 3], [4, 5, 6], [3.1, 'hello', '你好啊']]
fout.write(str(list_data)) 
fout.close()
"""
[[1, 2, 3], [4, 5, 6], [3.1, 'hello', '\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x95\x8a']]
"""

参考:
* 用python创建文件,文件名编号自动递增
* Python打开文件,将list、numpy数组内容写入txt文件中

猜你喜欢

转载自blog.csdn.net/u010472607/article/details/78853531