写入文本文件时遇到问题。文本文件被覆盖/剪切

时间:2019-03-24 04:17:18

标签: python text-files fwrite truncate prepend

我想将新数据写入文本文件的开头,每次导入新数据时,前一个数据向下移动1行,我希望一切都井井有条,但每次导入时都会删除。

代码:

import requests
from bs4 import BeautifulSoup
from datetime import datetime

response = requests.get('https://www.lotteryusa.com/michigan/lucky-4-life/')
soup = BeautifulSoup(response.text, 'html.parser')
date = soup.find(class_='date')
results = soup.find(class_='draw-result list-unstyled list-inline')
d = datetime.strptime(date.time['datetime'], '%Y-%m-%d')
Lucky = (d.strftime("%m%d%Y")+(',')+results.get_text()[:-20].strip().replace('\n',','))
print(Lucky)

with open("webscraper2noteppad++", "r+") as f:
    file = f.readlines()
    f.seek(0,0)
    f.write(Lucky)

也尝试这样做

with open("webscraper2noteppad++", "r+") as f:
    file = f.read()
    f.seek(0,0)
    f.write(Lucky + '\n')

但是我必须在现有数据和新数据之间放置10行。因此可以在不删除的情况下将其导入到顶部。

1 个答案:

答案 0 :(得分:0)

您可以先读取文件的内容,将其添加到新数据中,然后将所有内容写入文件中:

with open("webscraper2noteppad++", "r") as f:
    data = f.read()

with open("webscraper2noteppad++", "w") as f:
    f.write('{}{}{}'.format(lucky, '\n' if data else '', data))