Read txt file content in Python Web development-flask

Source: Internet
Author: User
In some cases, you need to read the TXT file from the Flask Web site to the directory. However, creating a file directly in the directory of the Flask Web site is inaccessible. From the site to find some information, and finally found that by writing a method to return TXT content is relatively simple and convenient, but this method is suitable for simple file reading and reading volume is relatively small. The detailed code is as follows:

@app. Route ('/<path> ')
def Today (path):
Base_dir = Os.path.dirname (__file__)
RESP = make_response (open (Os.path.join (base_dir, Path)). Read ())
resp.headers["content-type"]="Text/plan;charset=utf-8"
return RESP

Test method, create a Readm.txt file in the directory you want to catalog.

Run the program, Access/readme.txt, and return the following results:

Extended Knowledge Points:

Since a simple URL instance has been made in the previous code, the URL definition is the same as this one, except that the parameter name is different, as follows:

This time encountered a problem, when I put today's URL definition to the last side, in fact, the access is/<name> this URL, will always return hello xxx, and then put the code of this example to/<name> this interface, run again, Get the right results.


More articles, follow the public number "kick genius"

Read txt file content in Python Web development-flask

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.