代码之家  ›  专栏  ›  技术社区  ›  ASH

试图删除包含特定字符的文本文件中的行

  •  1
  • ASH  · 技术社区  · 5 年前

    我正在测试下面的代码,但它没有做我想做的。

    delete_if = ['#', ' ']
    with open('C:\\my_path\\AllDataFinal.txt') as oldfile, open('C:\\my_path\\AllDataFinalFinal.txt', 'w') as newfile:
        for line in oldfile:
            if not any(del_it in line for del_it in delete_if):
                newfile.write(line)
    print('DONE!!')
    

    基本上,我想删除任何包含“”字符的行(我想删除的行以“”字符开头)。另外,我想删除所有完全空白的行。我可以在进行中通过阅读列表中的项目来完成这项工作,还是需要多次通过文本文件来清除所有内容?短暂性脑缺血发作

    2 回复  |  直到 5 年前
        1
  •  0
  •   Kevin Quinzel    5 年前

    使用三元运算符怎么样?

     #First option: within your for loop
     line = "" if "#" in line or not line else line
    
     #Second option: with list comprehension
     newFile = ["" if not line or "#" in line else line for line in oldfile]
    

    我不确定三元是否有效,因为如果字符串为空,则应显示异常,因为“”不在空字符串中…怎么样

    #Third option: "Staging your conditions" within your for loop
    #First, make sure the string is not empty
    if line:
        #If it has the "#" char in it, delete it
        if "#" in line:
            line = ""
    #If it is, delete it
    else: 
        line = ""
    
        2
  •  1
  •   Darmaji    5 年前

    这很容易。请检查下面的代码:

    filePath = "your old file path"
    newFilePath = "your new file path"
    
    # we are going to list down which lines start with "#" or just blank
    marker = []
    
    with open(filePath, "r") as file:
        content = file.readlines() # read all lines and store them into list
    
    for i in range(len(content)): # loop into the list
        if content[i][0] == "#" or content[i] == "\n": # check if the line starts with "#" or just blank
            marker.append(i) # store the index into marker list
    
    with open(newFilePath, "a") as file:
        for i in range(len(content)): # loop into the list
            if not i in marker: # if the index is not in marker list, then continue writing into file
                file.writelines(content[i]) # writing lines into file
    

    关键是,我们需要先读所有的行。并逐行检查是否以 # 或者只是空白。如果是,则将其存储到列表变量中。之后,我们可以通过检查行的索引是否在marker中继续写入新文件。

    如果有问题请告诉我。