# -*- coding: UTF-8 -*-
import time
with open('write_file.txt', 'a') as f:
for i in range(5):
# 计算时间戳
timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
# 构造内容
contents = f'timestamp:{timestamp}, content:{i}'
# \n
# content = f'{contents}\n'
# \r\n
content = f'{contents}\r\n'
# 追加写入
f.write(content)
# 计算文件行数
file_path = 'write_file.txt' # 替换成你的文本文件路径
with open(file_path, 'r') as file:
lines = file.readlines()
num_lines = len(lines)
print("文本文件的行数:", num_lines)
''' # \n # content = f'{contents}\n' 文本文件的行数: 5 '''
''' # \r\n content = f'{contents}\r\n' 文本文件的行数: 10 '''
''' 参考: \r\n和\n的区别 回车/换行 在不同系统下的区别 https://blog.csdn.net/m0_51233386/article/details/134153294 Python 追加写入 txt 文件 https://geek-docs.com/python/python-file-tutorials/189_python_appends_to_a_txt_file.html#google_vignette Python获取文本文件的行数 https://blog.csdn.net/szial/article/details/131911477 '''