Importing a text file in Python2.7

This question already has an answer here:

  • In Python, how do I read a file line-by-line into a list? 35 answers

  • You can grab the file and loop the lines to do stuff with like this:

    filehandle = open("Hex.txt", "r")
    for line in filehandle:
        print (line)
    

    Or just grab the whole file into a string:

    with open("Hex.txt", "r") as myfile:
        data=myfile.read()
    

    There are actually several different ways to do this depending on what you are planning on doing with the data. Search around on StackOverflow but this should get you started.


    You don`t need to import text files. Import statement is for importing python built-in and external libraries and for importing .py script if you need to do so.

    For example:

    import sys
        print sys.path
    

    In case you need to do something with text file u can read it with following instructions:

    with open(file_path) as f:
        print f.read() #prints files content
    

    Read more about writing and reading files in Pythons documentation.

    If you meant something else in your question please provide more detailed information about what you ant to do.

    链接地址: http://www.djcxy.com/p/42362.html

    上一篇: 从文件中读取每行以Python列出

    下一篇: 在Python2.7中导入一个文本文件