0

I would like to read one line at a time and assigning that String to a variable in my Python script. Once this value is assigned I would like to delete that line from the txt file. Just now I have the next code:

import os

# Open file with a bunch of keywords
inputkeywordsfile = open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'r')

# Assigning
keyword = inputkeywordsfile.readline().strip()

So for example if the .txt file has this structure:

dog
cat
horse

The first time I run my script, dog will be assigned to keyword. The second time I run my script, cat will be assigned to keyword and dog will be deleted from the text file.

SOLVED:

readkeywordsfile = open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'r')
firstline = readkeywordsfile.readline().strip()
lines = readkeywordsfile.readlines()
readkeywordsfile.close()

del lines[0:1]

writekeywordsfile = open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'w')
writekeywordsfile.writelines(lines)
writekeywordsfile.close()

keyword = firstline
Alex
  • 517
  • 4
  • 9
  • 22
  • possible duplicate of [Deleting a specific line in a file (python)](http://stackoverflow.com/questions/4710067/deleting-a-specific-line-in-a-file-python) – Talvalin Apr 05 '14 at 17:23
  • 2
    In essence, you would need to open the file in read mode, read all the lines, close the file, then reopen the file in write mode and write the lines you want to keep. – Talvalin Apr 05 '14 at 17:25
  • 1
    Why not read the file into a list instead and use items from the list as per your need? – devnull Apr 05 '14 at 17:31
  • Thanks @Talvalin I was looking at the other thread and I think I almost have it, but I have a doubt here: `for line in lines: if line!="nickname_to_delete"+"\n": f.write(line)` In the question the user asks to delete a certain nickname but what I want is to delete each time the top line of the file. – Alex Apr 05 '14 at 17:45
  • What is the purpose of deleting the top line of the file each time? Why not read all the lines in one go as per @devnull's suggestion? – Talvalin Apr 05 '14 at 18:12
  • I am using one keyword each time I run the script, so each time I need a different keyword of the list. I don't want them to be repeated, so that's the point of reading the first line, using it and then delete it from the text file. Is there an option to do that? – Alex Apr 05 '14 at 18:24
  • Is the file updated often, other than this program removing items from the file? – Lasse V. Karlsen Apr 05 '14 at 18:33

2 Answers2

0

There could be a better solution perhaps. This worked for me as per my understanding of your question. During the executing each of the lines are assigned to the variable keyword . That is the reason I used print keyword to elaborate this fact. Moreover just for demonstrating I used time.sleep(5). During this pause of 5 seconds you can check your txt file, it will contain the data as you wished(When second line is assigned to a variable, the first line is removed from the txt file).

Code:

import os
import time

f = open("KeywordDatabase.txt","r")
lines = f.readlines()
f.close()
k = 0
for line in lines:
    if k == 0:
        keyword = line #Assignment takes place here
        print keyword
        f = open("KeywordDatabase.txt","w")
        for w in lines[k:]:
            f.write(w)
        k += 1
        f.close()
    else:
        keyword = line #Assignment takes place here
        print keyword
        f = open("KeywordDatabase.txt","w")
        for w in lines[k:]:
            f.write(w)
        f.close()
        k += 1
    time.sleep(5) #Time to check the txt file :)
ρss
  • 5,115
  • 8
  • 43
  • 73
0

Try this out and let me know how you get on. As a point to note, when dealing with file objects, the Pythonic way is to use the with open syntax as this ensures that the file is closed once you leave the indented code block. :)

import os

# Open file with a bunch of keywords
with open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'r') as inputkeywordsfile:

    # Read all lines into a list and retain the first one
    keywords = inputkeywordsfile.readlines()
    keyword = keywords[0].strip()

with open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'w') as outputkeywordsfile:
    for w in keywords[1:]:
        outputkeywordsfile.write(w)
Talvalin
  • 7,789
  • 2
  • 30
  • 40
  • I have solved this issue by myself. You can check the code in the main message. Is it right? – Alex Apr 05 '14 at 19:00
  • It's incorrect. The first call to `readline()` moves the file read index, so that `lines` only contains the remaining two keywords. Thus calling `del lines[0:1]` deletes the second keyword, leaving you just with `horse`. Remove the `del lines[0:1]` line and it'll work. – Talvalin Apr 05 '14 at 19:40