Akay
Akay

Reputation: 1

Rewrite files in Python

I am having issues with writing over textfiles in Python. As soon as I change open('tag.txt', 'r') to open('tag.txt', 'w') the file gets completely empty. In my code below I have managed to manipulate what I specifically want to print from my textfile but I can not get it to actually write it in the actual file so that I can only print that one in my code instead. I need to somehow create a code that when the "if columns[4] > localtime[3]:" it will rewrite the textfile with that new information so that I will not need to print the columns but so that I can print the textfile instead.

def alla_tag():
    localtime = time.asctime(time.localtime(time.time()))
    localtime = localtime.split(' ')
    tagfil = open('tag.txt', 'r')
    for line in open('tag.txt'):
        columns = line.split()
        if columns[4] > localtime[3]:
            print(columns[0] + ' ' + columns[1] + ' ' + columns[2] + ' ' + columns[3]  + ' ' + columns[4])
    tagfil.close()

Help someone? (Beginner to Python)

Upvotes: 0

Views: 422

Answers (3)

ZdaR
ZdaR

Reputation: 22964

You simply need to open the file in append mode by using the open(file_name, 'a'). So you need to edit the line of code where you are opening the file as:

tagfil = open('tag.txt', 'a')

If you open the file in w mode which stands for writable mode, then every time the previous contents of the file would be omitted and the new contents would override the previous saved content, to continue editing the previous file contents you need to open the file in append mode using the a flag in the open() function.

Upvotes: 5

cmbrooks
cmbrooks

Reputation: 47

One thing that I can see that could contribute to your problem is that your for loop is driven by open('tag.txt','r') Your for loop should look more like this: for line in tagfil:

What is happening is that you open a separate copy of the file at the begining of your for loop, so your changes are not saved to the variable tagfil.

Upvotes: 0

khelwood
khelwood

Reputation: 59166

I think you may need to open it in read mode (in a with block), read all the content, and then open it in write mode (in another with block) and write whatever you want to. Currently you're opening it for writing first, not writing anything to it, and then concurrently opening it for reading, which is not going to work.

Upvotes: 0

Related Questions