Contents
一、datetime模块
又长又臭,用时再查吧
部分习题与解答
1、假设你获取了用户输入的日期和时间如2020-1-21 9:01:30
,以及一个时区信息如UTC+5:00
,均是str
,请编写一个函数将其转换为timestamp:
"""
Input file
example1: dt_str='2020-6-1 08:10:30', tz_str='UTC+7:00'
example2: dt_str='2020-5-31 16:10:30', tz_str='UTC-09:00'
Output file
result1: 1590973830.0
result2: 1590973830.0
"""
def to_timestamp(dt_str, tz_str):
# your code here
pass
解题代码:
import sys
sys.path.append(r'D:\AAnaconda\Lib\site-packages')
from dateutil import parser
from datetime import datetime, timezone, timedelta
def to_timestamp(dt_str, tz_str):
time1 = parser.parse(dt_str)
hour = int(tz_str[3:tz_str.index(':')])
tz = timezone(timedelta(hours=hour))
dt = time1.replace(tzinfo=tz)
return dt.timestamp()
print(to_timestamp('2020-11-1 17:10:10', 'UTC+7:00'))
print(to_timestamp('2020-11-2 00:10:10', 'UTC+14:00'))
# 1604225410.0
# 1604225410.0
2、编写Python程序以选择指定年份的所有星期日。
题目说明:
"""
Input file
2020
Output file
2020-01-05
2020-01-12
2020-01-19
2020-01-26
2020-02-02
-----
2020-12-06
2020-12-13
2020-12-20
2020-12-27
"""
def all_sundays(year):
# your code here
解题代码:
import datetime
def all_sundays(year):
a = 1
dt = datetime.datetime(year=year, month=1, day=a)
while 1: # 先找出第一个星期日
if dt.isoweekday() == 7:
break
else:
a += 1
dt = datetime.datetime(year=year, month=1, day=a)
for week in range(0, 53): # 往后加一周,依次输出每日周日
t = datetime.timedelta(weeks=week)
sundays = (dt+t).date()
if sundays.year >= year + 1: # 若日期加到下一年,则停止
break
else:
print(sundays)
all_sundays(2019)
'''
2019-01-06
2019-01-06
2019-01-13
....
2019-12-22
2019-12-29
'''
二、文件与文件系统
1.打开模式 执行操作
‘r’ | 以只读方式打开文件(默认) |
---|---|
‘w’ | 以写入的方式打开文件,会覆盖已存在的文件 |
‘x’ | 如果文件已经存在,使用此模式打开将引发异常 |
‘a’ | 以写入模式打开,如果文件存在,则在末尾追加写入 |
‘b’ | 以二进制模式打开文件 |
‘t’ | 以文本模式打开(默认) |
‘+’ | 可读写模式(可添加到其他模式中使用) |
‘U’ | 通用换行符支持 |
2.文件对象方法 执行操作
f.close() | 关闭文件 |
---|---|
f.read([size=-1]) | 从文件读取size个字符,当未给定size或给定负值的时候,读取剩余的所有字符,然后作为字符串返回 |
f.readline([size=-1]) | 从文件中读取并返回一行(包括行结束符),如果有size有定义则返回size个字符 |
f.readlines() | 用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for… in … 结构进行处理 |
f.write(str) | 将字符串str写入文件 |
f.writelines(seq) | 向文件写入字符串序列seq,seq应该是一个返回字符串的可迭代对象 |
f.seek(offset, from) | 在文件中移动文件指针,从from(0代表文件起始位置,1代表当前位置,2代表文件末尾)偏移offset个字节 |
f.tell() | 返回当前在文件中的位置 |
f.truncate([size=file.tell()]) | 截取文件到size个字节,默认是截取到文件指针当前位置 |
3.os 模块中关于文件、目录常用的函数使用方法
getcwd() | 返回当前工作目录 |
---|---|
chdir(path) | 改变工作目录 |
listdir(path=’.’) | 列举指定目录中的文件名(’.‘表示当前目录,’…'表示上一级目录) |
mkdir(path) | 创建单层目录,如该目录已存在抛出异常 |
makedirs(path) | 递归创建多层目录,如该目录已存在抛出异常,注意:'E:\a\b’和’E:\a\c’并不会冲突 |
remove(path) | 删除文件 |
rmdir(path) | 删除单层目录,如该目录非空则抛出异常 |
removedirs(path) | 递归删除目录,从子目录到父目录逐层尝试删除,遇到目录非空则抛出异常 |
rename(old, new) | 将文件old重命名为new |
system(command) | 运行系统的shell命令 |
walk(top) | 遍历top路径以下所有的子目录,返回一个三元组:(路径, [包含目录], [包含文件]) |
以下是支持路径操作中常用到的一些定义,支持所有平台 | |
---|---|
os.curdir | 指代当前目录(’.’) |
os.pardir | 指代上一级目录(’…’) |
os.sep | 输出操作系统特定的路径分隔符(Win下为’\’,Linux下为’/’) |
os.linesep | 当前平台使用的行终止符(Win下为’\r\n’,Linux下为’\n’) |
os.name | 指代当前使用的操作系统(包括:‘posix’, ‘nt’, ‘mac’, ‘os2’, ‘ce’, ‘java’) |
4.os.path 模块中关于文件、目录常用的函数使用方法
函数名 | 使用方法 |
---|---|
basename(path) | 去掉目录路径,单独返回文件名 |
dirname(path) | 去掉文件名,单独返回目录路径 |
join(path1[, path2[, …]]) | 将path1, path2各部分组合成一个路径名 |
split(path) | 分割文件名与路径,返回(f_path, f_name)元组。如果完全使用目录,它也会将最后一个目录作为文件名分离,且不会判断文件或者目录是否存在 |
splitext(path) | 分离文件名与扩展名,返回(f_name, f_extension)元组 |
getsize(file) | 返回指定文件的尺寸,单位是字节 |
getatime(file) | 返回指定文件最近的访问时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算) |
getctime(file) | 返回指定文件的创建时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算) |
getmtime(file) | 返回指定文件最新的修改时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算) |
以下为函数返回 True 或 False | |
---|---|
exists(path) | 判断指定路径(目录或文件)是否存在 |
isabs(path) | 判断指定路径是否为绝对路径 |
isdir(path) | 判断指定路径是否存在且是一个目录 |
isfile(path) | 判断指定路径是否存在且是一个文件 |
islink(path) | 判断指定路径是否存在且是一个符号链接 |
ismount(path) | 判断指定路径是否存在且是一个挂载点 |
samefile(path1, paht2) | 判断path1和path2两个路径是否指向同一个文件 |
5.部分习题与解答
5-1 1、打开中文字符的文档时,会出现乱码,Python自带的打开文件是否可以指定文字编码?还是只能用相关函数?
答:可以指定文件的编码模式,在open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
中对encoding
参数设置就能指定文字编码,一般地encoding
使用utf8
5-2 编写程序查找最长的单词
输入文档: res/test.txt
题目说明:
"""
Input file
test.txt
Output file
['general-purpose,', 'object-oriented,']
"""
def longest_word(filename):
# your code here
pass
解:
分两种情况讨论?
① 若文本中单词的排列顺序是一行一个(暂且就认为这些乱七八糟的字母就是单词吧),如
rerojergoi
dgdfhgdf
dgfhgfhgfh
sgsgdf
dd
ddddgfhhheh
asgfasg_fs
gsgg
解题代码:
def longest_word(filename): # 以换行间隔单词
f = open(filename, 'r')
list1 = []
length = []
output = []
for each in f:
list1.append(each[:-1])
length.append(len(each[:-1]))
for a in list1:
if len(a) == max(length):
output.append(a)
return output
print(longest_word('test.txt')) # ['ddddgfhhheh']
②若单词的排列顺序是以逗号(,)间隔,如
fsgsgsgs,sgsgdsgsd,dsgds,g,dg,sgs,sgs,pdkjgisnj
解题代码:
def longest_word(filename): # 以逗号间隔单词
f = open(filename, 'r')
length = []
output = []
for each in f:
str1 = str(each)
list1 = str1.split(',', str1.count(',')+1)
for a in list1:
length.append(len(a))
for a in list1:
if len(a) == max(length):
output.append(a)
return output
print(longest_word('test1.txt')) # ['sgsgdsgsd', 'pdkjgisnj']