#218、将如下文件中内容读取出来,然后将其码值存入另一个文件中
#文件名为file.txt,文件中内容为“gloryroad”先读取出来数据,
#然后将字母的码值存入file1.txt文件中,10310811111412111411197100
with open("d:\\2019\\file.txt") as fp:
content=fp.read()
write_content=""
for i in content:
write_content+=str(ord(i))
with open("d:\\2019\\file1.txt","w") as fp:
fp.write(write_content)
with open("d:\\2019\\file1.txt") as fp:
print(fp.read())
#219、读取文件内容,统计出现次数最多的汉字,并将该汉字和次数打印出来,
with open("d:\\2019\\1.txt") as fp:
content=fp.read()
word_count={}
for i in content:
word_count[i]=content.count(i)
print(word_count)
for k,v in word_count.items():
if v==max(word_count.values()):
print("出现次数最多的汉字是%s,共出现了%s次" %(k,v))
#220、检验给出的路径是否是一个文件,检验给出的路径是否是一个目录,
#检验给出的路径是否是绝对路径
import os
def check_path(path):
if not os.path.exists(path):
print("路径不存在")
else:
if os.path.isfile(path):
print("是一个文件")
elif os.path.isdir(path):
print("是一个目录")
if os.path.isabs(path):
print("是一个绝对路径")
check_path("d:\\2019\\1")
#221、写一个函数,可以指定位置去替换文件内容。
#如果指定位置超出文件内容长度则在末尾添加,
#如果指定位置在文件内容中则从中修改
#如:文件a.txt中内容为”gggg”,替换内容为”gloryroad”,替换位置为1,则第二个g替换成gloryroad,则为”ggloryroadgg”,若替换位置为4, - 则超出gggg索引位置,直接在末尾添加,则为”gggggloryroad”
def replace_file_content(path,str,index):
'''path为文件路径,str为替换字符串,index为替换位置'''
with open(path) as fp:
content=fp.read().strip()
if index>=len(content):
with open(path,"a") as fp:
fp.write(str)
else:
write_content=content[0:index]+str+content[index+1:]
with open(path,"w") as fp:
fp.write(write_content)
replace_file_content("d:\\2019\\1.txt","gloryroad",0)
replace_file_content("d:\\2019\\1.txt","gloryroad",1)
replace_file_content("d:\\2019\\1.txt","gloryroad",3)
replace_file_content("d:\\2019\\1.txt","gloryroad",4)
#222、统计以上3题,写的3个python脚本的代码行数,不包括空行
count=0
with open("d:\\2019\\1.txt") as fp:
lines=fp.readlines()
for line in lines:
if line.strip()!="" and line[0]!="#":
count+=1
print(count)
#223、写一个函数,能通过传入的参数不同自动构造目录和目录下文件,规则如下:
#用户可以从控制台输入3个选项:1、2、q
#控制台传入”1”,则生成1个目录A,目录A下面有 2个文件a.txt,b.txt
#控制台传入”2”,则生成2个目录(目录A和目录B),目录A下面有2个文件a.txt和b.txt,目录B下面有2个文件b.txt和c.txt
#控制台q,则退出
#控制台输入其他数据,提示:输入有误!
import os
def create_dir_and_file(s):
if s=="1":
try:
os.mkdir("d:\\2019\\A")
except Exception as e:
print(e)
os.chdir("d:\\2019\\A")
print("已切换到A目录下")
with open("a.txt","w") as fp:
print("已创建a.txt")
with open("b.txt","w") as fp:
print("已创建b.txt")
elif s=="2":
try:
os.mkdir("d:\\2019\\A")
except Exception as e:
print(e)
try:
os.mkdir("d:\\2019\\B")
except Exception as e:
print(e)
os.chdir("d:\\2019\\A")
print("已切换到A目录下")
with open("a.txt","w") as fp:
print("已创建a.txt")
with open("b.txt","w") as fp:
print("已创建b.txt")
os.chdir("d:\\2019\\B")
print("已切换到B目录下")
with open("b.txt","w") as fp:
print("已创建b.txt")
with open("c.txt","w") as fp:
print("已创建c.txt")
elif s=="q":
exit()
else:
print("输入有误")
if __name__=="__main__":
try:
cmd=input("请输入1、2或q:")
except Exception as e:
print(e)
create_dir_and_file(cmd)
来源:CSDN
作者:猴子不想吃香蕉
链接:https://blog.csdn.net/Folivoraxue/article/details/103916216