【问题标题】:How to insert lines in file if not already present?如果不存在,如何在文件中插入行?
【发布时间】:2019-10-21 09:04:47
【问题描述】:

所以,我有多行的文本文件:

orange
melon
applez
more fruits
abcdefg

我有一个要检查的字符串列表:

names = ["apple", "banana"]

现在我想检查文件中的所有行,如果不存在的话,我想从名称列表中插入缺失的字符串。如果它们存在,则不应插入它们。

一般来说,这应该不难,但要处理所有的换行符,这是相当挑剔的。这是我的尝试:

if not os.path.isfile(fpath):
    raise FileNotFoundError('Could not load username file', fpath)

with open(fpath, 'r+') as f:
    lines = [line.rstrip('\n') for line in f]
    if not "banana" in lines:
        lines.insert(0, 'banana')
    if not "apple" in lines:
        lines.insert(0, 'apple')

    f.writelines(lines)
    print("done")

问题是,我的值不是插入新行而是附加的。 我也觉得我的解决方案通常有点笨拙。有没有更好的方法来自动插入丢失的字符串并处理所有换行符等?

【问题讨论】:

标签: python file insert


【解决方案1】:

您需要seek 到文件的第一个位置,并使用join 将每个单词写入一个新行,以覆盖其内容:

names = ["apple", "banana"]
with open(fpath, 'r+') as f:
    lines = [line.rstrip('\n') for line in f]
    for name in names:
        if name not in lines:
            # inserts on top, elsewise use lines.append(name) to append at the end of the file.
            lines.insert(0, name)

    f.seek(0) # move to first position in the file, to overwrite !
    f.write('\n'.join(lines))
    print("done")

【讨论】:

    【解决方案2】:

    首先使用readlines() 获取文件中所有用户名的列表,然后使用列表推导从names 列表中识别缺失的用户名。 创建一个新列表并将其写入您的文件。

    names = ["apple", "banana"]
    new_list = List()
    
    with open(fpath, 'r+') as f:
      usernames = f.readlines()
      res = [user for user in usernames if user not in names] 
      new_list = usernames + res
    
    with open(fpath, 'r+') as f:  
      for item in new_list:
            f.write("%s\n" % item)
    

    【讨论】:

      【解决方案3】:
      file_name = r'<file-path>' # full path of file
      
      names = ["apple", "banana"] # user list of word
      
      
      with open(file_name, 'r+') as f: # opening file as object will automatically handle all the conditions
          x = f.readlines() # reading all the lines in a list, no worry about '\n'
      
          # checking if the user word is present in the file or not
          for name in names:
              if name not in x: # if word not in file then write the word to the file
                  f.write('\n'+name )
      

      【讨论】:

        猜你喜欢
        • 2011-04-19
        • 2011-03-10
        • 1970-01-01
        • 2010-11-24
        • 2011-01-14
        • 2022-01-08
        相关资源
        最近更新 更多