Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python将分析代码插入到所有文件中_Python_Google Analytics - Fatal编程技术网

python将分析代码插入到所有文件中

python将分析代码插入到所有文件中,python,google-analytics,Python,Google Analytics,我正在尝试将google analytics脚本插入到我的所有HTML页面中,但当我再次运行该脚本时,文件的内容会重复 为什么我的脚本会复制文件内容并将其附加到文件末尾 如何将分析脚本添加到所有没有分析脚本的文件中 import fnmatch import os track_code = """ <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){

我正在尝试将google analytics脚本插入到我的所有HTML页面中,但当我再次运行该脚本时,文件的内容会重复

为什么我的脚本会复制文件内容并将其附加到文件末尾

如何将分析脚本添加到所有没有分析脚本的文件中

import fnmatch
import os

track_code = """
    <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-48664735-1', 'kylelk.github.io');
    ga('send', 'pageview');

    </script>
    """


matches = []
for root, dirnames, filenames in os.walk('.'):
    for filename in fnmatch.filter(filenames, '*.html'):
        matches.append(os.path.join(root, filename))

for file_name in matches:
    try:
        html_file=open(file_name, "r+")
        html_data = html_file.read()
        if "</head>" in html_data and not "UA-48664735-1" in html_data:
            print file_name
            html_data1=list(html_data)
            #find index of closing "head" tag
            html_data1.insert(html_data.find("</head>"), track_code)
            html_file.write("".join(html_data1))
            html_file.close()

        elif "</HEAD>" in html_data and not "UA-48664735-1" in html_data:
            print file_name
            html_data1=list(html_data)
            html_data 1.insert(html_data.find("</HEAD>"), track_code)
            html_file.write("".join(html_data1))
            html_file.close()
    except IOError:
        pass
import-fnmatch
导入操作系统
轨道_代码=”“”
(函数(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]| |函数(){
(i[r].q=i[r].q | |[]).push(参数)},i[r].l=1*新日期();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(窗口,文档,“脚本”,“www.google-analytics.com/analytics.js”,“ga”);
ga('create','UA-48664735-1','kylelk.github.io');
ga(‘发送’、‘页面浏览’);
"""
匹配项=[]
对于os.walk('.')中的根、目录名和文件名:
对于fnmatch.filter(文件名“*.html”)中的文件名:
matches.append(os.path.join(根目录,文件名))
对于匹配项中的文件名:
尝试:
html\u file=open(文件名为“r+”)
html\u data=html\u file.read()
如果html_数据中的“”而不是html_数据中的“UA-48664735-1”:
打印文件名
html_数据1=列表(html_数据)
#查找结束“头”标记的索引
html\u data1.insert(html\u data.find(“”),track\u代码)
html_file.write(“.”join(html_data1))
html_file.close()
html_数据中的“elif”,而非html_数据中的“UA-48664735-1”:
打印文件名
html_数据1=列表(html_数据)
html_数据1.insert(html_数据.find(“”),track_代码)
html_file.write(“.”join(html_data1))
html_file.close()
除IOError外:
通过

基本上,您在这里所做的是: 1.以读/写模式打开文件 2.读取整个文件内容,将内部文件指针定位在文件末尾 3.在当前文件指针的位置(即文件末尾)重写整个内容(使用添加的脚本)

您要做的是替换文件的内容。最简单、最安全的解决方案是:

  • 以只读方式打开文件
  • 阅读并关闭它
  • 将脚本添加到内容中
  • 以写入模式重新打开文件并写入新内容
  • 现在,由于更新的内容将比原始内容长,您也可以在写入之前重新定位内部文件指针(使用
    file.seek(0)