1.基础题:
检验给出的路径是否是一个文件:
检验给出的路径是否是一个目录:
判断是否是绝对路径:
检验给出的路径是否真实存在:
import os
import os.path
os.path.isfile("e:\\testdemo\\1.txt")
os.path.isdir("e:\\testdemo")
os.path.isabs("datalog.txt")
os.path.exists("e:\\test")
- 返回一个路径的目录名和文件名
os.path.dirname("e:\testdemo\a.py")
os.path.basename("e:\test\1.txt")
- 分离文件名与扩展名
os.path.splitext("e:\test\a.py")
- 找出某个目录下所有的文件,并在每个文件中写入“gloryroad”
import os
import os.path
for root,dirs,files in os.walk("e:\testdemo"):
for file in files:
file_path = os.path.join(root,file)
with open(file_path,"w",encoding="utf-8") as fp:
fp.write("gloryroad\n")
- 如果某个目录下文件名包含txt后缀名,则把文件后面追加写一行“被我找到了!”
import os
import os.path
for root,dirs,files in os.walk("e:\\"):
for file in files:
file_path = os.path.join(root,file)
if os.path.splitext(file_path)[1] == ".txt":
with open(file_path,"a",encoding="utf-8") as fp:
fp.write(u"被我找到了!\n")
- 命题练习:
1) 一个目录下只有文件(自己构造),拷贝几个文件(手工完成)
2 )用listdir函数获取所有文件,如果文件的创建时间是今天,那么就在文件里面写上文件的路径、
文件名和文件扩展名
3) 如果不是今天创建(获取文件的创建时间,并转化为时间格式,判断是否今天),请删除
4 )计算一下这个程序的执行耗时
import os
import os.path
import time
start_time = time.time()
for file in os.listdir("e:\\testman"):
os.chdir("e:\\testman")
#time.localtime(os.path.getctime(file))把文件的创建时间转换为时间元组
if time.strftime("%Y-%m-%d") == time.strftime("%Y-%m-%d",time.localtime(os.path.getctime(file))):
with open(file,"w",encoding="utf-8") as fp:
fp.write(os.path.abspath(file))
else:
os.remove(file)
elapse_time = time.time() - start_time
print("耗时:",elapse_time)
7.删除某个目录下的全部文件
import os
for file in os.listdir("e:\\testman"):
os.chdir("e:\\testman")
if os.path.isfile(file):
os.remove(file)
- 统计某个目录下文件数和目录个数
import os
import os.path
def count_file_and_dir_number(dir):
file_number = 0
dir_number = 0
if not os.path.exists(dir):
return 0,0
for root,dirs,files in os.walk(dir):
for i in dirs:
dir_number += 1
for file in files:
file_number += 1
return file_number,dir_number
print(count_file_and_dir_number("e:\\keyword_driven_proj"))
9. 删除某个目录下的全部文件(仅限一级目录)
算法:遍历所有的目录、文件,如果主目录等于一级目录,删除其下的文件
import os
import os.path
for root,dirs,files in os.walk("e:\\testman"):
if root == "e:\\testman"
for path in os.listdir(root):
os.chdir(root)
if os.path.isfile(path):
os.remove(path)
10. 使用程序建立一个多级的目录,在每个目录下,新建一个和目录名字一样的txt文件
"""
os.mkdir(str(i))
os.chdir(str(i))
创建目录,计入目录,然后有创建下一级目录
"""
import os
os.chdir("e:\\testman")
for i in range(3):
os.mkdir(str(i))
os.chdir(str(i))
with open(str(i)+".txt","w",encoding="utf-8") as fp:
pass
11. 查找某个目录下是否存在某个文件名
import os
def find_file(dir_path,file):
os.chdir(dir_path)
return os.path.exists(file)
print(find_file("e:\\testman","1.txt"))
def find_file2(dir_path,file):
for root,dirs,files in os.walk(dir_path):
if file in files:
return True
return False
print(find_file2("e:\\testman","1.txt"))
12. 用系统命令拷贝文件
import os
#windows
os.chdir("e:\\testman\\0")
os.system("copy 0.txt d:")
#linux
os.system("cp /home/1.txt /root/1.txt")
13. 输入源文件所在路径和目标目录路径,然后实现文件拷贝功能
import shutil
def copy_file(source,dest):
shutil.copy(source,dest)
copy_file("e:\\testman\\0\\0.txt","e:\\testman1\\0.txt")
14. 遍历某个目录下的所有图片,并在图片名称后面增加_xx
def parse_pic(path):
os.chdir(path)
for dir_or_file in os.listdir(path):
if os.path.splitext(dir_or_file)[1] == ".png":
new_name = os.path.splitext(dir_or_file)[0] + "_xx" + os.path.splitext(dir_or_file)[1]
os.rename(dir_or_file,new_name)
print(parse_pic("e:\\2020-02-22"))
15、遍历指定目录下的所有文件,找出其中占用空间最大的前3个文件
def get_max_three_files_size(path):
result = {}
for root,dirs,files in os.walk(path):
for file in files:
file_path = os.path.join(root,file)
result[file_path] = os.path.getsize(file_path)
return dict(sorted(result.items(),key=lambda x:x[1],reverse=True)[:3])
print(get_max_three_files_size("f:\\工作学习\\宋利红\\代码"))
16、过滤py源码中的#注释,另存为文件result.py,并执行result.py,断言是否执行成功
with open("e:\\testman\\b.py","r",encoding="utf-8") as file_obj:
for line in file_obj:
if not line.strip().startswith("#"):
with open("e:\\testman\\result.py","a",encoding="utf-8") as file_obj:
file_obj.write(line)
import os
os.chdir("e:\\testman")
os.system("py -3 result.py > assert.txt")
with open("e:\\testman\\assert.txt") as file_obj:
print("执行结果:",file_obj.read())
17、文件访问,提示输入数字 N 和文件 F, 然后显示文件 F 的前 N 行
n = int(input("请输入数字n:"))
file_path = input("请输入文件路径:")
with open(file_path,encoding="utf-8") as fp:
lines = fp.readlines()
for line in lines[:n]:
print(line)
n = int(input("请输入数字n:"))
file_path = input("请输入文件路径:")
with open(file_path,encoding="utf-8") as fp:
for i in range(n):
print(fp.readline())
18、从命令行接受1个路径如:c:\a\b\c\1.py, 实现1个函数创建目录a\b\c,创建文件1.py,实现1个函数删除已创建的目录及文件
import os
import os.path
file_path = input("请输入文件路径:")
def create(file_path):
dirs = os.path.split(file_path)[0]
file = os.path.split(file_path)[1]
if not os.path.exists(dirs):
os.makedirs(dirs)
os.chdir(dirs)
with open(file,"w") as fp:
pass
def remove(file_path):
dirs = os.path.split(file_path)[0]
file = os.path.split(file_path)[1]
os.chdir(dirs)
if os.path.exists(file):
os.remove(file)
if os.path.exists(dirs):
os.removedirs(dirs)
create(file_path)
remove(file_path)
19、有一个ip.txt,里面每行是一个ip,实现一个函数,ping 每个ip的结果,把结果记录存到ping.txt中,格式为ip:0或ip:1 ,0代表ping成功,1代表ping失败
算法:
1)、读出IP地址
2)、如果 “(0% 丢失)”存在写成功结果,否则写失败结果
#encoding=utf-8
import os
import os.path
with open("e:\\testman\\ip.txt",'r',encoding="utf-8") as fp1:
with open("e:\\testman\\ping.txt", 'w') as fp2:
for ip in fp1:
if ip.strip() !="":
if os.popen("ping "+ ip).read().find(u"%0 丢失"):
fp2.write(ip.strip()+ ":"+ "0\n")
else:
fp2.write(ip.strip()+ ":"+"1\n")
20、实现DOS命令执行功能,接受输入命令并执行,然后把执行结果和返回码打印到屏幕
import os
def run_dos_command(command):
print(os.system(command))
run_dos_command("dir")
21、文件访问
访问一存在多行的文件,实现每隔一秒逐行显示文本内容的程序,每次显示文本文件的 5
行, 暂停并向用户提示“输入任意字符继续”,按回车键后继续执行,直到文件末尾。
显示文件的格式为:
[当前时间] 一行内容,比如:[2016-07-08 22:21:51] 999370this is test
#encoding=utf-8
import os
import time
import traceback
with open("e:\\a.py","r",encoding="utf-8") as fp:
content = fp.readlines()
start = 0
try:
while 1:
for i in range(5):
time.sleep(1)
print("["+time.strftime("%Y-%m-%d %H-%M-%S")+"]"+content[start+i],end=" ")
start += 5
input("press any key to continue")
except Exception as e:
print("done!")
traceback.print_exc()
方法2:
#encoding=utf-8
def print_file(path):
import time
#当flag为True表示开始读取文件
flag = True
fp = open(path,encoding="utf-8")
while 1:
if flag == True:
for i in range(5):
time.sleep(1)
line = fp.readline()
#处理空行显示
len_s = len(line)
if len_s > 0 :
print("["+time.strftime("%Y-%m-%d %H:%M:%S")+"]"+line)
else :
print("EOF")
return
flag = False
command = input("请输入任意字符,并按回车键继续!")
if command is not None:
flag = True
fp.close()
print_file("e:\\a.py")
22、同时读写文件
with open("e:\\testman\\1.txt",encoding="utf-8") as fp:
for line in fp:
with open("e:\\testman\\2.txt","a",encoding="utf-8") as fp1:
fp1.write(line)
23、创建一个空文件
with open("e:\\testman\\11.txt","w") as fp:
pass
24、读取文件的前两行
with open("e:\\testman\\1.txt",encoding="utf-8") as fp:
for i in range(2):
print(fp.readline())
25、读取文件的奇数行
with open("e:\\testman\\1.txt",encoding="utf-8") as fp:
content = fp.readlines()
for i in range(0,len(content),2):
print(content[i])
26、在文件中写入一个列表的内容
with open("e:\\testman\\1.txt",encoding="utf-8") as fp:
lines = fp.readlines()
with open("e:\\testman\\2.txt","w",encoding="utf-8") as fp1:
fp1.write(lines)
with open("e:\\testman\\2.txt",encoding="utf-8") as fp2:
print(fp2.readlines())
27、在文件中的0、2、4位置写入当前的文件位置偏移量
with open("e:\\testman\\a.txt","w",encoding="utf-8") as fp:
fp.write(str(fp.tell()))
fp.seek(2,0)
fp.write(str(fp.tell()))
fp.seek(4,0)
fp.write(str(fp.tell()))
28、with写法读取文件内容
with open("e:\\testman\\a.txt","w",encoding="utf-8") as file_obj:
lines = file_obj.readlines()
29、统计一个文件中单词的个数
文件内容:
glory road ,wu lao shi
file,haha
women, man, love
with open("e:\\testman\\b.txt",encoding="utf-8") as fp:
content = fp.read()
content = content.replace(",","")
print(len(content.split()))
with open("e:\\testman\\b.txt",encoding="utf-8") as fp:
content = fp.read()
import re
print(len(re.findall(r"\b[a-z]+\b",content,re.I)))
30、将一个文件的所有单词倒序写入文件中
with open("e:\\testman\\b.txt",encoding="utf-8") as fp:
content = fp.read()
words = re.findall(r"\b[a-z]+\b",content,re.I)
with open("e:\\testman\\c.txt","w",encoding="utf-8") as fp1:
fp1.write("".join(words[::-1]))