文章目录
- 一、基础语法
- 1、sleep休眠
- 2、os系统操作
-
- 3、文件操作
- (1)文件读取模式详解
- (2)逐行读取文件
- (3)逐行写入文件
- 4、字符串操作
-
- 5、时间操作
-
一、基础语法
1、sleep休眠
import time
time.sleep(5)
2、os系统操作
(1)获取环境变量
import os
name = os.getenv("MY_NAME", "World")
print(f"Hello {name} from Python")
(2)os.path操作
import ospath_temp = 'E:\test.txt'
print(os.path.isdir(path_temp))
print(os.path.isfile(path_temp))
print(os.path.exists(path_temp))
script_path = os.path.abspath(__file__)
project_path = os.path.dirname(script_path)
3、文件操作
(1)文件读取模式详解
(2)逐行读取文件
file_path = 'E:\phone.txt'file_content= []
with open(file_path, 'r') as file:for line in file:file_content.append(line.strip())print(file_content)
(3)逐行写入文件
filename = "file.txt"
lines_to_append = ["这是第一行\n", "这是第二行\n", "这是第三行\n"]
with open(filename, "w") as file:for line in lines_to_append:file.write(line)
4、字符串操作
(1)字符串转义
image = cv.imread(r"E:\photo/naked_wife.jpg")
5、时间操作
(1)获取当前时间
import datetime
current_time = datetime.datetime.now()
print(current_time)
current_year = current_datetime.year
current_month = current_datetime.month
current_day = current_datetime.day
current_hour = current_datetime.hour
current_minute = current_datetime.minute
current_second = current_datetime.second
import time
timestamp = time.time()
current_time = time.ctime(timestamp)
import time
current_time_struct = time.localtime()
current_year = current_time_struct.tm_year
current_month = current_time_struct.tm_mon
current_day = current_time_struct.tm_mday
current_hour = current_time_struct.tm_hour
current_minute = current_time_struct.tm_min
current_second = current_time_struct.tm_sec
print(current_time_struct)
(2)时间格式化
import datetime
now = datetime.datetime.now()
now_str = now.strftime("%Y-%m-%d %H:%M:%S")
print(now_str)import time
timestamp = time.time()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
print(formatted_time)