python一道关于文件操作的题

题目

这道题是python核心编程里面的题,改编了一下(因为我只实现了一部分)。
不同的url有不同的后缀例如.com和.cn对于不同的后缀我们要把url存到不同的合法且正确的HTML文件中。

首先要先解决把不同的url存到不同的文件中。这里要用到os模块。我们要改变当前工作目录,把目录设置为你想要进行操作的目录os.chdir('C:/.../filetest.py'),然后把要进行操作的目录的路径传给now_file。在这个文件夹下有三个子文件夹,可以用os.listdir()[x]定位到你想用的文件夹的名字。最后要用os.path.join(path1, path2)合成一个完整目录再进行操作。

os.chdir('C:/.../filetest.py')
now_file = os.getcwd()
base_html = os.path.join(now_file, os.listdir()[0]) 
s = input('请输入你要保存的url信息:')
s1 = s.split( )
s2 = s1[1].split('.')[2][1] 
#s2可以定位到http://www.xxx.com中的'o'或者'n'来进行不同操作#
if s2 == 'o':
    handle_com(s, now_file, base_html)
else:
    handle_cn(s, now_file, base_html)

为什么要存入HTML文件中?因为这样比较好看,在这道题里我只是把url存入到了<h>标签里,因此可以不用导入jinja模板。当然了,这个方法比较笨,不过还没学jinja模板只好用笨方法了。
我们需要一个base.html文件并把要存取url的com.html文件已经cn.html文件放到一个文件夹下。开始的时候base.html文件里要存东西如下:

<html>
    <h1>
    </h1>
</html>

另外两个文件不用存东西。我们可以用循环把base.html文件中的标签遍历一遍并写入com.html或cn.html文件中,并在<h>标签里写入想要存的url。就像这样:

def handle_com(s, now_file, base_html):
    t = 0
    child_path = os.path.join(now_file, os.listdir()[2])
    f = open(base_html, 'r')
    f1 = open(child_path, 'w')
    for eachline in f:
        if t == 2:
            f1.write('        ' + s + '\n')
            f1.write(eachline)
        else:
            f1.write(eachline)
        t = t + 1
    f1.close()
    f.close()

这样就把url存入HTML文件中了。完整代码:

import os

def handle_com(s, now_file, base_html):
    t = 0
    child_path = os.path.join(now_file, os.listdir()[2])
    f = open(base_html, 'r')
    f1 = open(child_path, 'w')
    for eachline in f:
        if t == 2:
            f1.write('        '+ s +'\n')
            f1.write(eachline)
        else:
            f1.write(eachline)
        t = t + 1
    f1.close() 
    f.close()

def handle_cn(s, now_file, base_html):
    t = 0
    child_path = os.path.join(now_file, os.listdir()[1])
    f = open(base_html, 'r')
    f1 = open(child_path, 'w')
    for eachline in f:
        if t == 2:
            f1.write('        ' + s + '\n')
            f1.write(eachline)
        else:
            f1.write(eachline)
        t = t + 1
    f1.close()
    f.close()


os.chdir('C:/Users/.../filetest.py')
now_file = os.getcwd()
base_html = os.path.join(now_file, os.listdir()[0]) 
s = input('请输入你要保存的url信息:')
s1 = s.split( )
s2 = s1[1].split('.')[2][1] 
if s2 == 'o':
    handle_com(s, now_file, base_html)
else:
    handle_cn(s, now_file, base_html)
请输入你要保存的url信息:百度 https://www.baidu.com/ 百度一下,你就知道

可以把com.html文件用浏览器打开试一下。输入格式为网站名+空格+网址+空格+简单说明。
生成的com.html文件如下:

<html>
    <h1>
        百度 http://www.baidu.com/ 百度一下,你就知道
    </h1>
</html>

再发一遍,更改了几个小错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值