如果不存在,如何在文件中插入行?

How to insert lines in file if not already present?

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

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")

问题是,我的值没有插入到新行中,而是被追加了。 另外我觉得我的解决方案通常有点笨拙。有没有更好的方法来自动插入缺失的字符串并处理所有换行符等?

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 )

您需要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")

首先使用 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)