我正在抓取信息到文本文件,我正在尝试在顶部写日期。我有获取日期的方法,但不知道如何使用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()
答案 0 :(得分:3)
您无法在文件开头插入内容。您需要编写一个新文件,从您要插入的行开始,然后使用旧文件的内容完成。不像追加到最后,写入文件的开头实际上是非常低效的
此问题的关键是使用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")
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.
答案 1 :(得分:2)
只是为了给你提供想法
试试这个: -
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()
答案 2 :(得分:2)
要将日期写入您想要放置的文件的“顶部”:
newfile.write(InputDate)
newfile.write(Today)
在您打开文件之后以及其他任何内容之前。
答案 3 :(得分:1)
简单一个,如果您不将其称为def dosomething():
while selection == 1:
......
......
,那么它将抛出错误str
我已经刷新了代码以便更精确有效地使用..
TypeError: write() argument must be str, not list
结果将是:
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()