Python将行添加到正在写入的文件的顶部

2024-06-09 20:18:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我把信息刮到一个文本文件,并试图写在顶部的日期。我有抓取日期的方法,但不知道如何使用write函数放置在顶部。下面是我正在做的工作的精简版本。你知道吗

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

Tags: 方法函数import信息todaydatetimestringtitle
3条回答

要将日期写入要放置的文件的“顶部”,请执行以下操作:

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

在你打开文件之后,在其他事情之前。你知道吗

只是给你个主意

试试这是:-

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

不能在文件开头插入内容。您需要编写一个新文件,从要插入的行开始,然后以旧文件的内容结束。与追加到结尾不同,写入文件开头的效率非常非常低

这个问题的关键是使用^{}。构造完成后,可以在旧文件的顶部重命名它。你知道吗

代码:

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)

测试代码:

import datetime as dt
import tempfile
import shutil

insert_timestamp_in_file("file1")

文件1

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.

结果:

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.

相关问题 更多 >