1、时间戳
"""time时间戳"""
import time
timestamp = time.time()
print('当前时间戳:',timestamp)
print('当前的时间戳取整数:',int(timestamp))
print('当前时间戳保留3位小数后的整数:',int(timestamp*1000))
time.sleep(1)
print('时间暂停1s后打印输出')
current_time = time.strftime('%Y-%m-%d %H:%M:%S')
print('输出时间格式:',current_time)
运行结果:
D:\Study\pythonProject\venv\Scripts\python.exe D:/Study/pythonProject/Test1127.py
当前时间戳: 1764214761.1232276
当前的时间戳取整数: 1764214761
当前时间戳保留3位小数后的整数: 1764214761123
时间暂停1s后打印输出
输出时间格式: 2025-11-27 11:39:22
2、文件读取
name,age
张三,18
李四,20
王五,19
示例一:
"""文件操作"""
with open(file=r'D:\Study\pythonProject\file\20251127.CSV',mode='r',encoding='utf8') as f:
print('读取文件数据第一行',f.readline())
print('读取文件所有对象:',f.read())
with open(file=r'D:\Study\pythonProject\file\20251127.CSV',mode='r',encoding='utf8') as f:
readlines = f.readlines()
print('读取文件所有行,并且为列表:',readlines)
运行结果:
D:\Study\pythonProject\venv\Scripts\python.exe D:/Study/pythonProject/Test1127.py
读取文件数据第一行 name,age
读取文件所有对象: 张三,18
李四,20
王五,19
读取文件所有行,并且为列表: ['name,age\n', '张三,18\n', '李四,20\n', '王五,19\n']
示例二:
with open(file=r'D:\Study\pythonProject\file\2025112701.CSV',mode='w',encoding='utf8') as f:
print('文件写入单条数据:',f.write('何必,25\n'))
message = ['张无忌,25\n','张君宝,23\n']
message_write = f.writelines(message)
print('文件写入多条数据:',message_write)
with open(file=r'D:\Study\pythonProject\file\2025112701.CSV',mode='a',encoding='utf8') as f:
print('文件写入单条数据:',f.write('何必,25\n'))
message = ['张无忌,25\n','张君宝,23\n']
message_write = f.writelines(message)
print('文件末尾追加写入多条数据:',message_write)
运行结果:
D:\Study\pythonProject\venv\Scripts\python.exe D:/Study/pythonProject/Test1127.py
文件写入单条数据: 6
文件写入多条数据: None
文件写入单条数据: 6
文件末尾追加写入多条数据: None
Process finished with exit code 0
2025112701.CSV
何必,25
张无忌,25
张君宝,23
何必,25
张无忌,25
张君宝,23
示例三:
"""先读后写"""
with open(file=r'D:\Study\pythonProject\file\2025112701.CSV',mode='r+',encoding='utf8') as f:
print('读取文件:',f.readlines())
print('写入文件:',f.writelines('张三丰,101\n'))
"""先写后读"""
with open(file=r'D:\Study\pythonProject\file\2025112701.CSV',mode='r+',encoding='utf8') as f:
print('写入文件:',f.writelines('殷天正,98\n'))
print('读取文件:',f.readlines())
运行结果:
D:\Study\pythonProject\venv\Scripts\python.exe D:/Study/pythonProject/Test1127.py
读取文件: ['何必,25\n', '张无忌,25\n', '张君宝,23\n', '张三丰,101\n', '殷天正,98\n']
写入文件: None
写入文件: None
读取文件: ['何必,25\n', '张无忌,25\n', '张君宝,23\n', '张三丰,101\n', '殷天正,98\n', '张三丰,101\n']
Process finished with exit code 0
2025112701.CSV
何必,25
张无忌,25
张君宝,23
张三丰,101
殷天正,98
张三丰,101
殷天正,98
1万+

被折叠的 条评论
为什么被折叠?



