简体   繁体   中英

Python - Writing up to a specific line in a file then starting back at line 1

word = input("\nPlease enter the word you want to look up > ")
file = open("recents.txt", 'a')
file.write("\n" + word)
file.close()

For my dictionary program I have a recent searches feature, and as of now when you search for a word it adds that word on a new line in the file. But how would you make it so you have the 10 most recent searches, so on the 10th line it does not add any more and starts again at line 1, replacing old searches?

Open for both read/write (a+ mode), then read whole file (file object is behave like array of lines) then keep max 9 of them ([:9] slicing).

Then erase whole file content (put cursor on start with seek and truncate the rest) Write lines back (now they not contains 10th) (lines already contains \\n, so join with empty string is correct) And finally write current word at end of file.

with f as open("recents.txt", 'a+'):
  lines = list(f)[:9]  # store to max 9 lines
  f.seek(0)
  f.truncate()
  f.write(''.join(lines)) # write it back
  f.write(word + "\n")

You can use a list of the contents and rewrite them. Also, you should use with to open the file:

word = input("\nPlease enter the word you want to look up > ")
with open("recents.txt", 'r') as file:
    contents = file.readlines()
    if len(contents) == 10:
        contents = contents[-1:] + contents[:-1]
        contents[0] = word + "\n"
    else:
        contents.append("\n"+word)
with open("recents.txt", "w") as file:
    for i in contents:
        file.write(i)

Or you could use file.seek() to move the pointer to the beginning of the list:

word = input("\nPlease enter the word you want to look up > ")
with open("recents.txt", 'r+') as file:
    contents = file.readlines()
    if len(contents) == 10:
        contents = contents[-1:]+contents[:-1]
        contents[0] = word + "\n"
        file.seek(0,0)
        file.truncate()
        for i in contents:
            file.write(i)
    else:
        file.write("\n"+word)

If your word count is to remain limited to a small number than you can use pickle to store dict object containing your last insertion and dict of words. Here for the case I am taking 5 words to be stored and suppose last insertion was made in 3 position. Your dict would look something like:

import pickle
recent_dict = { "last_insertion":3, "word_dict" : {1 : "enormous", 2 : "erronous" , 3: "embarras", 4 : "paragmatic", 5: "benevolent"}}
with open("recents.word", 'wb') as f:
    pickle.dump(recent_dict, f)

Now while adding a new word , say temparate :

n_word = "temperate"
recent_dict = pickle.load(open("temp.txt", 'rb'))
recent_dict["word_dict"][recent_dict["last_insertion"] + 1] = n_word
recent_dict["last_insertion"] = recent_dict["last_insertion"] + 1
# and then again dump this info through pickle 

The collections module in the standard library has a deque container. Have you looked into using that?

Sample code:

from collections import deque

filename = "recents.txt"
maxlen = 9

try:
  recents = deque((w.rstrip() for w in open(filename, 'r')), maxlen=maxlen)
except FileNotFoundError:
  recents = deque(maxlen=maxlen)
recents.append(input("\nPlease enter the word you want to look up > "))
print(*recents, file=open(filename, 'w'), sep='\n’)

This rewrites the recents.txt file from scratch every time, which may not be a big deal if it only contains 9 entries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM