2

I am scraping info to a text file and am trying to write the date at the top. I have the method to grab the date but have no clue how I can use the write function to place at top. Below is a stripped down version of what I am working on.

import re
import urllib2
import json
from datetime import datetime
import time

now = datetime.now()
InputDate = now.strftime("%Y-%m-%d")
Today = now.strftime("%B %d")

header = ("Today").split()

newfile = open("File.txt", "w")

### Irrelevant Info Here ###

string = title"\n"+info+"\n"
#newfile.write(header)
newfile.write(string)
print title+" written to file"

newfile.close()
0

4 Answers 4

4

You can't insert something at the beginning of a file. You need to write a new file, starting with the line you want to insert, then finish with the contents of the old file. Unlike appending to the end, writing to the start of the file is really, really inefficient

The key to this problem is to use a NamedTemporaryFile. After you finish constructing it, you then rename it on top of the old file.

Code:

def insert_timestamp_in_file(filename):
    with open(filename) as src, tempfile.NamedTemporaryFile(
            'w', dir=os.path.dirname(filename), delete=False) as dst:

        # Save the new first line
        dst.write(dt.datetime.now().strftime("%Y-%m-%d\n"))

        # Copy the rest of the file
        shutil.copyfileobj(src, dst)

    # remove old version
    os.unlink(filename)

    # rename new version
    os.rename(dst.name, filename)

Test Code:

import datetime as dt
import tempfile
import shutil

insert_timestamp_in_file("file1")

file1

I am scraping info to a text file and am trying to write the date at
the top. I have the method to grab the date but have no clue how I can
use the write function to place at top. Been trying for 2 days and all.

Results:

2018-02-15
I am scraping info to a text file and am trying to write the date at
the top. I have the method to grab the date but have no clue how I can
use the write function to place at top. Been trying for 2 days and all.
Sign up to request clarification or add additional context in comments.

1 Comment

Im struggling with this one but I am not great at this. I for sure see the theory and believe it works. Thank you very much
2

To write the date to the 'top' of the file you would want to put:

newfile.write(InputDate)
newfile.write(Today)

after where you open the file and before anything else.

1 Comment

Wow thats super simple and worked like a charm. Thank you.
2

Just to give you idea

Try this:-

import re
import urllib2
import json
from datetime import datetime
import time
now = datetime.now()
InputDate = now.strftime("%Y-%m-%d")
Today = now.strftime("%B %d")
#start writing from here
newfile = open("File.txt", "a")
newfile.write(InputDate+"\n")
newfile.write("hello Buddy")
newfile.close()

Comments

1

Simple One will be, if you will not call it as a str then it will throw an error TypeError: write() argument must be str, not list

I have rfreshed teh code to be more precise and effective use..

import re
from datetime import datetime
import time

now = datetime.now()
InputDate = now.strftime("%B"+" "+"%Y-%m-%d")
newfile = open("File.txt", "a")
string = "Hi trying to add a datetime at the top of the file"+"\n"
newfile.write(str(InputDate+"\n"))
newfile.write(string)
newfile.close()

Result will be:

February 152018-02-15
Hi trying to add a datetime at the top of the file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.