Learning record 06: How python saves data to local txt


foreword

Deep learning or other similar places need to save time-named txt files for local storage of losses or other key parameters


Tip: The following are the codes and explanations introduced in this article

1. Code

import time		# python里的日期模块


def savePara():
    date = time.strftime('%Y-%m-%d %H:%M:%S').split()		# 按空格分开,这里宫格是我自己添加的
    														# 可以按照自己的习惯添加然后分离出自己需要的时间
    print(date)     # ['2021-07-22', '16:11:00']
    hour_minute = date[1].split(':')
    print(hour_minute)      # 时,分,秒

	# 文件路径
    filepath = './logs/' + date[0] + '-' + hour_minute[0] + '-' + hour_minute[1] \
               + hour_minute[2] + '.txt'
    # 打开文件
    file = open(filepath, 'w')
    # 读取当前时间
    now = time.strftime('%Y-%m-%d %H:%M:%S')
    # 写入数据
    file.write(now + '   ' + 'loss: ' + str(2) + '\n')
    # 刷新缓存
    file.flush()


savePara()

2. Description of the main functions

1. Local time

time.strftime('format') The returned time is the local time. The specific returned time depends on the expression of the format. The format has different expressions, representing different time formats, as follows:

%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身

Examples are as follows:

date1 = time.strftime('%y')
print(date1)			
# 输出为21

date2 = time.strftime('%Y')
print(date2)			
# 输出为2021

## 同样也可以组合表达,除了%,其他符号均为原本自己形式
date = time.strftime('%Y-%m-%d %H:%M:%S')
print(date)	
# 输出为2021-08-13 15:35:08

2. Save the file

filepath = './logs/' + date[0] + '-' + hour_minute[0] + '-' + hour_minute[1] \
               + hour_minute[2] + '.txt'
file = open(filepath, 'w')
file.write(now + '   ' + 'loss: ' + str(2) + '\n')
file.flush()

(1) Path format

filepathIt is used to store the file address path. The previous one ./logs/means the logs folder in the same directory as your python. If not, you need to create it manually. If you don’t add this section, it will be saved in the same directory as your python file. . If you want to write more perfect, you can add a function to judge whether there is logsa folder in the current directory, and if not, it will be created automatically.

os.path.exists(path) 	# 判断一个目录是否存在
os.getcwd()					# 获得当前路径

os.makedirs()							# 创建多级目录
os.makedirs('./logs/loh/log')		# 表示在logs目录下创建文件夹,如果不存在logs文件夹会自己创建logs文件夹,等价于下面
os.makedirs('logs/loh/log')

os.mkdir()			# 创建单级目录	
os.mkdir('logs/loh/log')		# 这里是相对路径,会在loh文件夹里创建log文件夹,如果前面的目录不存在,会报错
os.mkdir('logs')					# 在当前目录下创建logs文件夹,如果已经存在会报错

(2) Open the file

open(filepath, 'w')wIt is used to open the file specified by the path, and the operation corresponding to the subsequent specification includes the following common operations:

x			# 写模式,新建一个文件,如果该文件已存在则会报错
r			# 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
w			# 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
a			# 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

(3) Refresh buffer

file.flush()It is used to refresh the buffer, that is, write the data in the buffer to the file immediately, and clear the buffer at the same time, instead of passively waiting for the output buffer to be written. If there is no such item, an error will be reported when multiple files are continuously created and written, and the memory is not cleared in time.

3. Read the file file

(1) Read each line in txt

filepath = “xxxxx”
with  open(filepath) as f
	fileContent(读取文件存储变量的) = f.readlines()

Guess you like

Origin blog.csdn.net/qq_43180908/article/details/119673865