【问题标题】:Run every N lines from a different file within the file is running?运行文件中的不同文件中的每 N 行是否正在运行?
【发布时间】:2020-12-14 02:37:47
【问题描述】:

我有一个在 python 中运行的大文件,我将它拆分,因为它消耗了太多的内存......但是,结果是 250 个 python 代码文件,我也一次运行一个文件并且是太费时间了...我只想从大文件中一次执行 5 行而不拆分它并且几乎不使用任何内存...

文件:

import requests
from bs4 import BeautifulSoup
lines = 5
with open('finito.py') as bigfile:
# Execute every 5 lines?? 

Finito_file 示例:

url = 'https://result.com/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
c=soup.find_all('h2')[0:4]
print(c,file=open("links.txt", "a"))

从大文件来看,每5行是这样的……

示例输出:

[]
[<h2 class="tile--hero__headline"><span style="overflow:hidden;display:block"><span>Home For the Holidays</span></span></h2>, <h2 class="tile--hero__headline"><span style="overflow:hidden;display:block"><span>Disney+ Original Special</span></span></h2>, <h2 class="tile--hero__headline"><span style="overflow:hidden;display:block"><span>The Great Christmas Light Fight</span></span></h2>, <h2 class="tile--hero__headline"><span style="overflow:hidden;display:block"><span>Big Sky</span></span></h2>]

这是finito.py中每5行代码的结果...所有结果都将保存在links.txt中

【问题讨论】:

  • 你可以试着写一个函数

标签: python python-3.x database file exec


【解决方案1】:

使用readline()逐行读取文件,而不将整个文件存储在内存中。

def nextFive(file):
    lines = []
    for line in range(5):
        line = file.readline()
        if line:
            lines.append(line)
    return lines

bigFile = open('finito.py')
code = nextFive(bigFile)
while len(code) > 0:
    # Execute every 5 lines of code
    for line in code:
        exec line in globals(), locals()
    code = nextFive(bigFile)
bigFile.close()

【讨论】:

  • 谢谢雷蒙德·穆蒂亚巴! !但是,第 14 行,在 code = nextFive(bigFile) NameError: name 'bigFile' is not defined
  • 我在定义 bigfile 时没有将 f 大写。我刚刚编辑了我的答案以纠正错误。
  • 再次感谢 Raymond!但我m really sorry to bother you again... there is a bug problem every time I execute the program... When I debug it in Pycharm, it open bigFile = open('finito.py'), but it doesn't read anything and when it goes to code = nextFive(bigFile) and def... it return False and close the program because it didnt 在文件中找到了任何东西...我m trying to fixed but I dont 看看怎么样??
  • 我编辑了我的代码以修复一些错误。此外,如果 'finito.py' 中的代码有错误,exec line 将不会运行。在您的示例 finito 文件中,print(c,file=open("links.txt", "a")) 将导致错误,因为您无法在 print() 中设置 file = open("links.txt", "a")
  • 雷蒙德·穆蒂亚巴,非常感谢! ! !......我真的很感激......我想把反馈给无限加给你,但我的声誉不到15......代码运行良好......它对我的工作方式是exec (line) 而不是 globals() 中的 exec 行,locals().... 非常感谢! ! !
猜你喜欢
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
  • 2011-06-05
  • 2021-08-16
  • 1970-01-01
相关资源
最近更新 更多