读取文件内容并在浏览器中显示

-1 投票
1 回答
694 浏览
提问于 2025-04-17 15:02

我正在尝试用flask来实现以下功能。

我在本地磁盘上有一个文件,这个文件很大,所以我只想读取文件的前20行。

我该如何读取这个文件并在浏览器上显示它的内容呢?

有没有什么建议或者提示?谢谢!

1 个回答

1

像这样,应该可以工作

import webbrowser

# firstly you need to make write to an html file that will have the top 20 lines 
# you can do that using 

top_lines_file = open("shows.html", "w")
i = 1
while i in range(1,21):
    top_lines_file.write("write something to the file")
    i += 1
    # this will iterate over the file and write to it 20 times
top_lines_file.close() # close the file

# now you need to pass the path of the html file to the webbrowser object
webbrowser.open("file://" + path/to/the/html/file) 
# this will open the webbrowser with your html file 

撰写回答