【问题标题】:Having problems writing to text files. Text files being overwritten/cut写入文本文件时出现问题。被覆盖/剪切的文本文件
【发布时间】:2019-03-24 04:17:17
【问题描述】:

我想将新数据写入我的文本文件的开头,每次导入新数据时,以前的数据都会向下移动 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 行。所以可以在上面导入而不删除。

【问题讨论】:

  • 你能显示预期的文件内容吗?

标签: python text-files fwrite truncate prepend


【解决方案1】:

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

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

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

【讨论】:

  • 这行得通,但它附加在底部,我想把它放在前面。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 2012-04-15
  • 2016-08-15
相关资源
最近更新 更多