gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:14:44 25 4
gpt4 key购买 nike

我正在将信息抓取到一个文本文件中,并试图将日期写在顶部。我有获取日期的方法,但不知道如何使用写入功能将其置于顶部。下面是我正在处理的内容的精简版本。

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

最佳答案

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

这个问题的关键是使用NamedTemporaryFile .完成构建后,您可以在旧文件之上重命名它。

代码:

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.

关于Python - 将行添加到正在写入的文件的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48819972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com