首页 > 解决方案 > 如果文件中不存在,则从字典中写入某个键的值

问题描述

因此,下面的脚本会从文件中查找关键字,index.html并将这些关键字的值写入不同的文件style.css中。

from collections import OrderedDict

    keyword = {
    "row": '''
    .row {
    display: -ms-flexbox;
    display: flex; 
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -15px;
    margin-left: -15px;
    }'''
    #etc
        }   

with open('index.html', 'r') as file:
   with open('style.css', 'a') as newfile:
      lines = file.readlines()
      for line in lines:
         if 'class="' in line:
            to_replace = line.split('"')[1].split()
            to_replace = OrderedDict.fromkeys(to_replace)
            for key in to_replace:
                if key in keyword:
                    newfile.write(keyword[key])
                    keyword[key] = ''

HTML 文件:

<div class="row"></div> etc

但有一个问题。当我运行脚本 N 次时,它应该只输出一次值style.css

.row {
        display: -ms-flexbox;
        display: flex; 
        -ms-flex-wrap: wrap;
        flex-wrap: wrap;
        margin-right: -15px;
        margin-left: -15px;
        }

在我的情况下,它会在我运行脚本时多次写入“行”的值。

如何防止价值重复?

我试图做某事,但它不起作用:

with open('index.html', 'r') as file:
  to_read = open('style.css')
  to_write = open('style.css', 'a')
  lines = file.readlines()
  for line in lines:
     if 'class="' in line:
        to_replace = line.split('"')[1].split()
        to_replace = OrderedDict.fromkeys(to_replace)
        for key in to_replace:
          if key in keyword:
            if key in to_read.read():
              break
            else:
              to_write.write(keyword[key])         
              keyword[key] = ''

标签: python

解决方案


发生这种情况是因为您以模式 ( )打开style.css文件。这意味着每次打开该文件时,它都会继续在第一个空行上写入。相反,您要做的是使用模式,如果文件不存在,它将创建文件并在其中写入。下次您运行它时,它将清除文件并从头开始写入,就像您刚刚创建它一样。appendopen('style.css', 'a')'w+'

所以,而不是open('style.css', 'a')使用open('style.css', 'w+'),你的问题就解决了。

编辑

要使用不同的文件名,只需为您的文件选择一个基本名称,例如style.css. 我们要做的是根据目录中的文件为每个文件附加一个数字。然后在保存文件之前,只需检查要保存文件的目录,os.listdir()看看那里有哪些文件。假设您运行脚本 3 次。会有[style_1.css, style_2.css, style_0.css]。现在您可以对它们进行排序以获取[style_0.css, style_1.css, style_2.css]并使用files_list[-1]. 拆分 by'.'然后 by'_'以获取一个数字,然后将其递增。我将向您展示代码,以便更容易理解:

filename = sorted(os.listdir(dir_to_css_files))[-1]
number = filename.split('.')[0].split('_')[-1]
n = str(int(number) + 1)
new_file = 'style_ + number + '.css'

使用python结构

我不确定您在做什么,但这是等待脚本完成、使用所需值填充字典然后将其保存到文件中的方式。如果再次运行该脚本,它将擦除该文件并将新值保存到相同的文件名。

d = dict()

with open('index.html', 'r') as file:
  lines = file.readlines()
  for line in lines:
     if 'class="' in line:
        to_replace = line.split('"')[1].split()
        to_replace = OrderedDict.fromkeys(to_replace)
        for key in to_replace:
            if key in keyword:
                d[key] = keyword[key]
                keyword[key] = ''

  with open ('style.css', 'w+') as new_file:
    new_file.write(str(d))

推荐阅读